Create JSON object in STRING as a Particle.variable

I have tried a search… I am trying to get one Ajax call to return multiple variables, instead of many calls. This is a simplified version of what I am trying.

So, I’m trying to create a JSON object within the STRING type of Particle.variable() like this:

  char myJSON[255] = "";
  snprintf(myJSON, 255, "{\"current\":{\"temp\":%d,\"humidity\":%d,\"dewpoint\":%d}}", int(outdoorTemp), int(relHumidity), int(dewPoint));
  strcpy(conditions, myJSON);

and it displays (as valid JSON) on the monitor like this:

but my Ajax call:

function getConditions(){
  var condURL = "https://api.spark.io/v1/devices/" + deviceID + "/" + "conditions" + "/?access_token=" + accessToken;
    $.getJSON(condURL, function(data) {
      alert(JSON.stringify(data));
  });
}

when returned, includes all of the escaping:

{"cmd":"VarReturn","name":"conditions","result":"{\"current\":{\"temp\":92,\"humidity\":59,\"dewpoint\":76}}","coreInfo":{"last_app":"","last_heard":"2016-07-31T15:23:58.583Z","connected":true,"last_handshake_at":"2016-07-31T15:22:53.180Z","deviceID":"53ff6c066678505541432367","product_id":0}}

which is of course valid JSON as it treats my pseudo-object as a string (as it should, I guess).

Is there any way to hack this to work?

1 Like

Not tested, but something like this should work where the alert call is currently:

var obj = JSON.parse(data.result);
console.log("data:", obj);

@rickkas7

You can see that the encapsulating quotes around the conditions member are causing the issue…

I may be barking up the wrong tree here. I thought I could be cleverer.

:wink:

Right, but inner backslashed escaped of quotes should be occurring during your JSON.stringify call because there are part of a JSON string that’s already in double quotes. By skipping the JSON.stringify and instead parsing the data.result with JSON.parse(data.result) you should get a JSON object back.

1 Like

Yeah, I see that.

It would be nice if we could have something like this:

Particle.variable("myName", myObject, JSON);

Thanks for setting me straight!

3 Likes