JSON is something relatively new to me. I have found the site http://www.jsoneditoronline.org/ to be VERY useful as I design JSON files and as I write code to encode JSON data.
On the encoding side, I followed some sample code to get started. That code worked, but it used char[] logic, and it seemed overly complex to me.
As an experiment, I used 100% “string logic” in the following function that maintains a Particle.variable named dStateJSON. The function works, and the code seems simpler to me. I’m curious to get other people’s thoughts, and to know if there might be an even simpler way to encode JSON.
// ----------------------------------------------------------------------------------------------------------------
void update_dStateJSON() {
bool firstDoor = TRUE;
String jsonString = "{\"gnode\": {\"version\": \"1.0\", \"message\": \"" + gnodeMessage + "\", \"doors\": [ ";
for (int i = 0; i < NUMDOORS; i++) {
if (! door[i].state == UNKNOWN) {
if (firstDoor) {
firstDoor = FALSE;
} else {
jsonString = jsonString + ","; // each array element after the first must start with a comma
}
jsonString = jsonString // construct a json string for the door object
+ "{"
+ "\"id\":" + door[i].id + ","
+ "\"state\":\"" + doorStateText[door[i].state] + "\","
+ "\"statetime\":\"" + String(door[i].stateTime) + "\","
+ "\"message\":\"" + door[i].actionMessage + "\","
+ "\"button\":\"" + doorNextAction[door[i].state] + "\""
+ "}";
}
}
jsonString = jsonString + "]}}";
dStateJSON = jsonString; // dStateJSON is the Particle.variable
return;
}
// ----------------------------------------------------------------------------------------------------------------
In HTML, I use the jquery command “$.getJSON” to obtain the JSON produced by the above function. A prettified version of of the command’s output follows:
{
"gnode": {
"version": "1.0",
"message": "",
"doors": [
{
"id": 1,
"state": "OPEN",
"statetime": "2017-05-24T00:10:55Z",
"message": "",
"button": "Close Door"
},
{
"id": 2,
"state": "CLOSED",
"statetime": "2017-05-24T00:10:55Z",
"message": "",
"button": "Open Door"
},
{
"id": 3,
"state": "CLOSED",
"statetime": "2017-05-24T00:10:55Z",
"message": "",
"button": "Open Door"
},
{
"id": 4,
"state": "CLOSED",
"statetime": "2017-05-24T00:10:55Z",
"message": "",
"button": "Open Door"
}
]
}
}