In this esp32 tutorial we will check how to deserialize a JSON string into an object, using Espruino running on the ESP32. For an explanation about performing the inverse operation (serializing an object into a JSON string), please check this previous post.
As we did before, we will leverage the JSON global object, which makes available a method called parse, which allows to convert a valid JSON string into an object.
The tests were performed using a DFRobot’s ESP32 module integrated in a ESP32 development board.
We will start by declaring a JSON string representing an object with two properties, a number and a string. This is a very simple object but you can test with a more complex one, as long as the string is a valid JSON.
You can use this tool to validate and format your JSON and this to minify it to a single line string.
var jsonString = '{"prop1":20,"prop2":"A string"}';
Now, to parse this JSON string to a JavaScript object, we simply need to call the parse method of the global JSON object. This method receives as input the JSON string and returns the corresponding JavaScript object.
var obj = JSON.parse(jsonString);
Now, to confirm that everything was correctly parsed, we will print the object. Additionally, we will access each of its properties using the dot operator, to confirm that it is indeed working like any regular object.
console.log(obj); console.log(obj.prop1); console.log(obj.prop2);
The final source code can be seen below.
var jsonString = '{"prop1":20,"prop2":"A string"}'; var obj = JSON.parse(jsonString); console.log(obj); console.log(obj.prop1); console.log(obj.prop2);
To test the code, simply run the previous script on the Espruino IDE. You should get an output similar to figure 1. As can be seen, the JSON was correctly deserialized to an object and we can work with it like any regular JavaScript object.
Figure 1 – Result of the deserialization of the JSON string.