ESP32: Parsing JSON

The objective of this post is to explain how to parse JSON messages with the ESP32 and the ArduinoJson library.


Introduction

The objective of this post is to explain how to parse JSON messages with the ESP32 and the ArduinoJson library. We assume a previous installation of the ESP32 support for the Arduino IDE. If you haven’t done it yet, pcheck here how to do it.

Please note that this code will be very similar to the one in the tutorial about parsing JSON on a ESP8266, which you can consult here.

You can install the library via Arduino IDE library manager, being this the easiest way to do it. Just search for ArduinoJson on the search bar, as shown in figure 1, and you should get the option to install it. At the time of writing, the latest version is 5.9.0, which is the one used for the tutorial.

ArduinoJson library v5.9.0

Figure 1 – ArduinoJson library installation via Arduino IDE library manager.

Although there’s still no support mentioned for the ESP32 in the list of supported devices, the code works fine, as we will see.


The code

First of all, we need to include the previously mentioned ArduinoJson library, so we can have access to the JSON parsing functionality. Since we are going to do the actual parsing in the main loop function, we will just open the serial connection on the setup function, in order to print the output of our program.

#include <ArduinoJson.h>

void setup() {

  Serial.begin(115200);
  Serial.println();

}

After that, on the loop function, we will declare a variable to hold the JSON message to parse. Note that the \ characters are used for escaping double quotes on the declared string. This is needed because JSON names require double quotes.

char JSONMessage[] = " {\"SensorType\": \"Temperature\", \"Value\": 10}"; //Original message

The structure of the JSON message is shown bellow without the escaping characters. Note that this is a dummy example that shows a possible message structure for sending information of a sensor.

{
"SensorType" : "Temperature",
"Value" : 10
}

Important: The JSON parser modifies the string [1] and because of that its content can’t be reused, even though the string will be the same during the whole program execution. So, we declare it inside the main loop and not as a global variable, guaranteeing that when the main loop function returns, it is freed and a new variable is allocated again in the next call to the loop function.

After that, we will declare an object of class StaticJsonBuffer, which corresponds to a pre-allocated memory pool to store the JSON object tree. Since this is a memory pool, we need to specify the size. This is done in a template parameter (the value between <> in the code bellow), in bytes. We passed a value 300 bytes, which is enough for the string to be parsed.

StaticJsonBuffer<300> JSONBuffer; //Memory pool

Next, we call the parseObject method on the StaticJsonBuffer object, passing as parameter the JSON string. This method call returns a reference to an object of class JsonObject, which we will use to obtain the parsed values.

JsonObject& parsed = JSONBuffer.parseObject(JSONMessage); //Parse message

We can call the success method on the JsonObject to confirm that the parsing occurred without errors, as shown bellow.

if (!parsed.success()) { //Check for errors in parsing
  Serial.println("Parsing failed");
  delay(5000);
  return;
}

Now, we will use the subscript operator to get the parsed values by their names, from the JsonObject. In other words, we use square brackets and the names of the parameters to get their values. Note that the strings to be used are the ones from the original JSON message: “SensorType” and “Value”.

const char * sensorType = parsed["SensorType"]; //Get sensor type value
int value = parsed["Value"]; //Get value of sensor measurement

The final code with the printing of these values can be seen bellow.

#include <ArduinoJson.h>

void setup() {

  Serial.begin(115200);
  Serial.println();

}

void loop() {

  Serial.println("Parsing start: ");

  char JSONMessage[] = " {\"SensorType\": \"Temperature\", \"Value\": 10}"; //Original message

  StaticJsonBuffer<300> JSONBuffer;                         //Memory pool
  JsonObject& parsed = JSONBuffer.parseObject(JSONMessage); //Parse message

  if (!parsed.success()) {   //Check for errors in parsing

    Serial.println("Parsing failed");
    delay(5000);
    return;

  }

  const char * sensorType = parsed["SensorType"]; //Get sensor type value
  int value = parsed["Value"];                    //Get value of sensor measurement

  Serial.print("Sensor type: ");
  Serial.println(sensorType);
  Serial.print("Sensor value: ");
  Serial.println(value);

  Serial.println();
  delay(5000);

}


Testing the code

To test the code, upload it to the ESP32 and open the Arduino IDE serial monitor. You should start getting an output similar to figure 2, which presents the values obtained after parsing the original message.


ESP32 Parsing JSON

Figure 2 – Output of the JSON parsing program on the ESP32.


Related content


Related posts


References

[1] https://bblanchon.github.io/ArduinoJson/doc/pitfalls/

 

Technical details

  • ArduinoJson library: v5.9.0.
Advertisements
This entry was posted in ESP32 and tagged , , , , , , , , , . Bookmark the permalink.

2 Responses to ESP32: Parsing JSON

  1. Pingback: ESP32: Creating JSON message | techtutorialsx

  2. Pingback: ESP32: Sending JSON messages over MQTT | techtutorialsx

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s