Monday, December 9, 2024
ESPExplainerHow ToIoT HardwaresIoT Software&ToolsTutorials/DIY

ESP8266 Parsing JSON

The objective of this post “ESP8266 Parsing JSON” is to explain how to parse simple JSON on the ESP8266, using the ArduinoJson library. If you are not friendly with NodeMCU using Arduino IDE, Visit this: Arduino Support for ESP8266 with simple test code

Recommended: GPIO pins of ESP8266 and How to use efficiently

Recommended: NodeMCU ESP8266 OTA (Over-the-Air) using Arduino IDE

ESP8266 Parsing JSON

We will create a simple program to parse a JSON string simulating data from a sensor and print it to the serial port. we will use the ArduinoJson library, which provides easy to use classes and methods to parse JSON. The GitHub page of the library can be consulted here.

Arduino JSON is very helpful Library for encoding and decoding of JSON. You can installed ArduinoJSON Library via Arduino library manager.

Search AruinoJSON in Library manger.

Alternative method is Clone the repository.

  • Run the command git clone https://github.com/bblanchon/ArduinoJson.git
  • Configure your compiler to add the folder ArduinoJson/src/ to the list of include folders (-I /path/to/ArduinoJson/src/ on GCC command line)

How to use ArduinoJSON.h

First of all, we will include the library that implements the parsing functionality.

#include "ArduinoJson.h"

Since this library has some tricks to avoid problems while using it, this post will just show how to parse a locally created string, and thus we will not use WiFi functions. So, we will just start a Serial connection in the setup function.

1
2
3
4
5
6
void setup() {
  Serial.begin(115200);
  Serial.println();  //Clear some garbage that may be printed to the serial console
}

Main loop

main loop function of this program, we will declare our JSON message, that will be parsed. The \ characters are used to escape the double quotes on the string, since JSON names require double quotes.

char JSONMessage[] ="{\"SensorType\":\"Temperature\",

This simple structure is given below

1
2
3
4
{
"SensorType" : "Temperature",
"Value" : 10
}

JSON parser modifies the string and thus its content can’t be reused. So we declare the string inside the main loop and not as a global variable, even though its content is always the same in this program. This way, the variable is local and when the main loop function returns, it is freed and a new variable is allocated again in the next call to the loop function.

Now, we need to declare an object of class StaticJsonBuffer. It will correspond to a pre-allocated memory pool to store the object tree and its size is specified in a template parameter (the value between <> bellow), in bytes.

1
StaticJsonBuffer<300> JSONBuffer;

We declared a size of 300 bytes, which is more than enough for the string we want to parse. The author of the library specifies here two approaches on how to determine the buffer size. Personally, I prefer to declare a buffer that has enough size for the expected message payload and check for errors in the parsing step. ArduinoJSON library also supports dynamic memory allocation. Here we can check the differences between static and dynamic JsonBuffer.

Next, we call the parseObject method on the StaticJsonBuffer object, passing the JSON string as argument. This method will return a reference to an object of class JsonObject.

1
JsonObject&  parsed= JSONBuffer.parseObject(JSONMessage);

To check if the JSON was successfully parsed, we can call the success method on the JsonObject instance.

1
2
3
4
5
6
if (!parser.success()) {
  Serial.println("Parsing failed");
  return;
}

After that, we can use the subscript operator to obtain the parsed values by their names. Check here some information about the subscript operator. In other words, this means that we use square brackets and the the names of the parameters to obtain their values, as shown bellow.

1
2
const char * sensorType = parsed["SensorType"];
int value = parsed["Value"];

The whole main function is shown bellow. We included some extra prints to separate each iteration of the loop function and to show how the original string is modified when parsed. We need to print it char by char because the parser introduces \0 characters and thus, if we used Serial.println(JSONMessage), we would just see the content until the first \0 character.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
void loop() {
  Serial.println("——————");
  char JSONMessage[] = " {\"SensorType\": \"Temperature\", \"Value\": 10}"; //Original message
  Serial.print("Initial string value: ");
  Serial.println(JSONMessage);
  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.println(sensorType);
  Serial.println(value);
  Serial.print("Final string value: ");
  for (int i = 0; i < 31; i++) { //Print the modified string, after parsing
    Serial.print(JSONMessage[i]);
  }
  Serial.println();
  delay(5000);
}

Testing the code

To test the code, simply compile it and upload it to your ESP8266. After that, open the Arduino IDE serial monitor. GitHub page of this library is very well documented, visit here. Also, I strongly encourage you to check the example programs that come with the installation of the library, which are very good for understanding how it works.


I hope you like this post “ESP8266 Parsing JSON”. Do you have any questions? Leave a comment down below!

Thanks for reading. If you like this post probably you might like my next ones, so please support me by subscribing my blog.

We have other tutorials with ESP32 that you may find useful:

You may like also:


Upvote on Reddit

 

Harshvardhan Mishra

Hi, I'm Harshvardhan Mishra. Tech enthusiast and IT professional with a B.Tech in IT, PG Diploma in IoT from CDAC, and 6 years of industry experience. Founder of HVM Smart Solutions, blending technology for real-world solutions. As a passionate technical author, I simplify complex concepts for diverse audiences. Let's connect and explore the tech world together! If you want to help support me on my journey, consider sharing my articles, or Buy me a Coffee! Thank you for reading my blog! Happy learning! Linkedin

One thought on “ESP8266 Parsing JSON

Leave a Reply

Your email address will not be published. Required fields are marked *