The objective of this micropython tutorial is to explain how to encode a JSON message using MicroPython and the ujson library on the ESP32.
The objective of this post is to explain how to encode a JSON message using MicroPython and the ujson library on the ESP32. You can check how to enable the MicroPython support in this previous post. Also, if you need a guide on parsing JSON, check this previous tutorial.
First of all, we need to import the ujson module, which is done with the following command:
1 import ujson
Important: at the time of writing, ujson was one of the modules included in the MicroPython firmware, so we can just import it without any additional procedure. Nevertheless, if you can’t import it out of the box, the module may no longer be included by default and need to be manually installed.
The example JSON message we will try to get is the one bellow. It is simulating a possible message from an IoT device, having a type of device (temperature sensor) and some dummy measurement values.
So, after executing the previous code, we should get an output similar to figure 1. As can be seen, we have a dictionary structure with some name-value pairs. Note that the string representation of the Python dictionary is very similar of a JSON string.
Figure 1 – Content of the Python dictionary.
To finalize, we will now convert the dictionary to the JSON string, by using the dumps function of the ujson module. This method receives as input the dictionary and returns its JSON string representation. After invoking this function, we will print the result.
1 encoded = ujson.dumps(dict) 2 print(encoded)
The final result can be seen bellow in figure 2, where the encoded string is printed. Note that the output is very similar to the string representation of the dictionary we got before, but the names and values are now between double quotes instead of just single ones, which is how JSON if formatted.
Figure 2 – Final output of the JSON encoding program.
NOTE: This article is written by Nuno Santos who is an kindly Electronics and Computers Engineer. live in Lisbon, Portugal. you could check the original article here. He had written many useful tutorials and projects about ESP32, ESP8266, If you are interested, you could check his blog to know more.