Encoding data in JSON is popular for sending data over the Internet and also for storing data.
You can encode a Python List or dictionary in JSON format and then decode it back into a list or dictionary as illustrated in the diagram below:
Note: if you prefer video then I’ve create a YouTube video that covers this- How to Encode, Send and Receive JSON Data Using the Pythom MQTT Client
You will first need to import the json module
To encode a python dictionary or list use json.dumps(data) as show below:
data_out=json.dumps(brokers_out) # encode object to JSON
To convert from a JSON string to a Python object use json.loads(json_string) as show below:
m_in=json.loads(m_decode) #decode json data
I’ve created a simple Python script that demonstrates the process.
The first part of the script encodes and decodes a Python Dictionary.
The second part of the script encodes a Python Dictionary Publishes the Data to the MQTT broker, then receives the data and decodes it back into a dictionary.
You can download the demo script here.
Here is a screen shot of what it looks like when run.
Notice the Python objects is converted to a string by the json.dumps() function.
Now we run the second part of the script which publishes the JSON data and then receives the Data and decodes it back into a dictionary.
Here is the on_message Callback which receives the messages and converts it to a dictionary.
def on_message(client, userdata, msg): topic=msg.topic m_decode=str(msg.payload.decode("utf-8","ignore")) print("data Received type",type(m_decode)) print("data Received",m_decode) print("Converting from Json to Object") m_in=json.loads(m_decode) #decode json data print(type(m_in)) print("broker 2 address = ",m_in["broker2"])
Related Tutorials :
- My Python Working Notes
- Send JSON Data using the Mosquitto_pub client
- Send a File Using MQTT -MQTT Examples
- Encrypting MQTT Payloads with Python – Example Code
- Simple Python MQTT Data Logger