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.

wordle

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,&amp;s,"B_Pressure", bprs);
jsonEncode(NEXTJSON,&amp;s,"DS_TempInside", tin);
jsonEncode(NEXTJSON,&amp;s,"DS_TempOutside", tout);
jsonEncode(NEXTJSON,&amp;s,"DS_TempAttic", tatt);
jsonEncode(NEXTJSON,&amp;s,"DH_Humidity", dhhumi);
v = system_get_free_heap_size();
jsonEncode(NEXTJSON,&amp;s,"SYS_Heap", v);
v = millis()/1000;
jsonEncode(LASTJSON,&amp;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.

Loading

Share This:
FacebooktwitterredditpinterestlinkedintumblrFacebooktwitterredditpinterestlinkedintumblr
Social tagging: >

8 Responses to A Tiny Footprint ESP8266 Arduino IDE JSON Encoder

  1. Sukesh says:

    Have you tried this?
    I am planning to use it for similar scenario so would like to know if there were any pitfalls.

    https://github.com/marcoschwartz/aREST/tree/master/examples/ESP8266

    • facebook-profile-picture Dave St. Aubin says:

      Thanks for bringing the aREST API to my attention.

      While I have not used the aREST API you have referenced, I shall keep it in mind as a possible option. But it is very similar to the Arduino Yun bridge. I have used that without any problems. And the Spark Core (now Particle) also supports function calls and exposing variables with the value returned in JSON format. I also have experience using the Spark Core. A maximum of 10 variables could be exposed; that constraint limited it’s usefulness.

      If I was going to use the aREST library, I would find out if there are limits to the number of variables or functions you can call. I would also run some tests to evaluate the reliability and stability of the API.

      • Sukesh says:

        Hi Dave,
        Thanks for the response.

        I don’t see any limitations mentioned for this library.

        Also I found some special mode for resource constrained devices as well.
        Lightweight mode (BETA)

        Btw, I used the ArduinoJson library for my current scenario just for parsing small set of json. Not sure how it works when the data becomes more complicated though.

        • facebook-profile-picture Dave St. Aubin says:

          I recently completed a porting of the AWS API to the ESP8266 using the Arduino IDE. The API includes a complete set of JSON encode/decode functions. While I prefer the EspressIF SDK for code development, I currently plan to use the AWS JSON interface when needed.

          The tiny footprint JSON encoder from this post was just a stop-gap for me. It certainly is great to now be able to leverage the code endorsed by Amazon, the biggest gorilla in the room.
          Here is a brief post and link to an API for AWS for ESP8266.

  2. javier melendrez says:

    Sorry! After teh sentence…. "..Two short sketch functions, that’s it:.." appears an empty rectangle!
    Can you read that functions again?
    Thanks!!

  3. kixak says:

    Thanks a ton for this post. That's saved my day!!!!!
    It s 3 years old but still absolutely up-to-date.
    Actually I ve spent 4 days [nights 😉 ] or more wondering why I cant get anything from the ESP8266 server (I listened with ajax-request from my Android device through WIFI, using Cordova).

    And it was this missing line "Access-Control-Allow-Origin: *" that caused my app to discard everthing!!!

    Adding this line to the ESP8266 server:
    server.sendHeader("Access-Control-Allow-Origin","*");
    Ahead of the old one:
    server.send(200, "text/plain", JSONmessageBuffer);
    Has done the trick ;]

    THANKS AGAIN.

Leave a Reply