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, check 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.

If you prefer a video tutorial, please check my YouTube channel below.

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://arduinojson.org/v5/doc/pitfalls/

Technical details

  • ArduinoJson library: v5.9.0.

16 thoughts on “ESP32: Parsing JSON”

  1. Pingback: ESP32: Creating JSON message | techtutorialsx

  2. Pingback: ESP32: Creating JSON message | techtutorialsx

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

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

  5. Pingback: ESP32 Arduino Websocket server: Receiving and parsing JSON content | techtutorialsx

  6. Pingback: ESP32 Arduino Websocket server: Receiving and parsing JSON content | techtutorialsx

  7. Pingback: ESP32 Arduino Websocket server: Receiving and parsing JSON content – Arduino Boards News

  8. Pingback: ESP32 Arduino Websocket server: Receiving and parsing JSON content – Arduino Boards News

  9. can i able to control esp32 pins with jason file without prior initialization( eg: jason in http.getstring() holds the data of pin no. INPUT/OUTPUT high or low)

    1. Hi!

      Yes you can! Instead of using a statically initialized string, simply pass the result of the HTTP request to the parseObject method.

      As long as the JSON contains the information you are looking for, then you should be able to access the field that holds the data of the pin and use that value to control the pin.

      Best regards,
      Nuno Santos

  10. can i able to control esp32 pins with jason file without prior initialization( eg: jason in http.getstring() holds the data of pin no. INPUT/OUTPUT high or low)

    1. Hi!
      Yes you can! Instead of using a statically initialized string, simply pass the result of the HTTP request to the parseObject method.
      As long as the JSON contains the information you are looking for, then you should be able to access the field that holds the data of the pin and use that value to control the pin.
      Best regards,
      Nuno Santos

Leave a Reply

Discover more from techtutorialsx

Subscribe now to keep reading and get access to the full archive.

Continue reading