In this tutorial we will check how to deserialize a JSON string in an object, using Espruino running on the ESP32. The tests were performed using a DFRobot’s ESP32 module integrated in a ESP32 development board.
Introduction
In this 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.
The code
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);
Testing the code
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.
Related posts
- ESP32 Espruino: Converting an object to a JSON string
- ESP32 Espruino: Listing property names of objects
- ESP32 Espruino: Creating simple JavaScript objects
- ESP32 MicroPython: Parsing JSON
- ESP32 MicroPython: Encoding JSON
- ESP8266: Parsing JSON
- ESP8266: Parsing JSON Arrays
- ESP8266: Encoding JSON messages
- Python: Parsing JSON
- Flask: Parsing JSON data
- ESP32 Arduino Websocket server: Receiving and parsing JSON content
- ESP32 Picoweb: Serving JSON content
- ESP32: Sending JSON messages over MQTT
- ESP32: Creating JSON messages
- ESP32: Parsing JSON