ESP32 Espruino: Deserializing JSON

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.

ESP32 espruino Deserialize JSON

Figure 1 – Result of the deserialization of the JSON string.


Related posts

Advertisements
This entry was posted in ESP32 and tagged , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s