As I recently migrated from the ESP8266 SDK to the Arduino IDE, I was disappointed to discover that many of the SDK features were not supported with the simplified Arduino IDE. Notably, the JSON encoding/decoding library.
I tried to add pre-built libraries from several internet repositories. But none of them would work in the Arduino environment. And all I needed was a simple encoder, built from the values captured from my sensors. So I ended up creating a simple, flat encoder myself. One with minimal sketch code. I hope this may also suite someone else’s needs as well.
Here it is. Two short sketch functions, that’s it:
#define ONEJSON 1
#define FIRSTJSON 2
#define NEXTJSON 3
#define LASTJSON 4
<span style="line-height: 1.5;">void jsonAdd(String *s, String key,String val) {</span>
*s += '"' + key + '"' + ":" + '"' + val + '"';
}
void jsonEncode(int pos, String * s, String key, String val) {
switch (pos) {
case ONEJSON:
case FIRSTJSON:
*s += "{\r\n";
jsonAdd(s,key,val);
*s+= (pos==ONEJSON) ? "\r\n}" : ",\r\n";
break;
case NEXTJSON:
jsonAdd(s,key,val);
*s+= ",\r\n";
break;
case LASTJSON:
jsonAdd(s,key,val);
*s+= "\r\n}";
break;
}
}
And now for some example calls to these functions:
//First build the response header String s = "HTTP/1.1 200 OK\r\n"; s += "Access-Control-Allow-Origin: *\r\n"; s += "Content-Type: application/json\r\n\r\n"; //Then add the JSON string to the response //Last parameter read from sensor jsonEncode(FIRSTJSON,&s,"B_Pressure", bprs); jsonEncode(NEXTJSON,&s,"DS_TempInside", tin); jsonEncode(NEXTJSON,&s,"DS_TempOutside", tout); jsonEncode(NEXTJSON,&s,"DS_TempAttic", tatt); jsonEncode(NEXTJSON,&s,"DH_Humidity", dhhumi); v = system_get_free_heap_size(); jsonEncode(NEXTJSON,&s,"SYS_Heap", v); v = millis()/1000; jsonEncode(LASTJSON,&s,"SYS_Time", v);
The resulting response message header and JSON string:
HTTP/1.1 200 OK
Access-Control-Allow-Origin: *
Content-Type: application/json
{
"B_Pressure":"29.0",
"DS_TempInside":"86.4",
"DS_TempOutside":"90.1",
"DS_TempAttic":"111.6",
"DH_Humidity":"30.0",
"DH_Temperature":"91.4",
"SYS_Heap":"32568",
"SYS_Time":"1610"
}
Notice that I added
Access-Control-Allow-Origin: *
to the response header. This is needed if you use Javascript AJAX to read the ESP8266 JSON string. Javascript will not allow cross-domain access without this in the response header. This example opens access to all domains. You can replace the * with the domain you wish to limit access to your ESP8266 from.
Hope you find this information useful.
![]()
