How to Send JSON Data Over MQTT with Python

send-json-data-mqttEncoding 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:



send-json-data-diagram

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

import json

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 using the link below

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.

Json-encode-decode-pytho

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.

send-data-json-mqtt-example

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"])

Summary

JSON is a very popular format for encoding data and sending it across networks and also for storing it.

Python makes it easy to create JSON encoded data strings and to decode them.

Related Tutorials :

Facebooktwittergoogle_plusredditpinterestlinkedinmail

Leave a Reply

Your email address will not be published. Required fields are marked *