Archives for ESP8266 Arduino IDE JSON

A Tiny Footprint ESP8266 Arduino IDE JSON Encoder

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:


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


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.

Share This: