In this ESP32 tutorial we will check how to print a JSON string in a prettified format, which makes it easier for a human to read. The tests shown here were performed using an ESP32 board from DFRobot.
In this ESP32 tutorial we will check how to print a JSON string in a prettified format, which makes it easier for a human to read. We will be using the ESP32 and the ArduinoJson library.
We have already covered in detail on this tutorial how to serialize JSON using the ESP32 and the ArduinoJson library. The code shown here will be very similar, except for the serializing function we will call at the end.
So, instead of printing a minified JSON string without spaces and line breaks like we did in the previous post, the function we will call to serialize the JSON document will output a nicely formatted string with some spaces and line breaks.
Naturally, in a final application where we will be sending the JSON using some protocol (HTTP, websockets, etc..), it is more efficient to use the minified version.Nonetheless, for debugging, it makes it much easier to interpret the JSON string if we use the approach shown on this tutorial.
This tutorial targets version 6 of ArduinoJSON. The tests shown here were performed using an ESP32 board from DFRobot.
We will start by including the ArduinoJson.h library, so all the functionalities we need to serialize the JSON will become available.
Moving on to the Arduino setup function, we will start by opening a serial connection. We will later use it to output the JSON string.
After that, we are going to declare an object of class StaticJsonDocument. Recall from the previous tutorial that this object will hold the memory representation of our object. This memory will be allocated on the stack.
We need to specify the capacity of the StaticJsonDocument as a template parameter. The value is specified in bytes. We will use a value of 100, which is enough for our object. For a more accurate estimation, you can use this assistant.
Next we will take care of adding the members of our JSON. We are going to build the following structure, for testing purposes:
To add members to our StaticJsonDocument we will use the  operator, as shown below: