如何在python中的mqtt代理上发布json数据?

时间:2017-03-11 06:11:19

标签: python mqtt paho

我正在尝试在MQTT代理主题上发布JSON数据。这是源代码,我试过 -

import paho.mqtt.client as mqtt
import json
# Define Variables
MQTT_HOST = "localhost"
MQTT_PORT = 1883
MQTT_KEEPALIVE_INTERVAL = 45
MQTT_TOPIC = "irisPayload"

MQTT_MSG=json.dumps({"sepalLength": "6.4","sepalWidth":  "3.2","petalLength": "4.5","petalWidth":  "1.5"});
# Define on_publish event function
def on_publish(client, userdata, mid):
    print "Message Published..."
# Initiate MQTT Client
mqttc = mqtt.Client()

# Register publish callback function
mqttc.on_publish = on_publish

# Connect with MQTT Broker
mqttc.connect(MQTT_HOST, MQTT_PORT, MQTT_KEEPALIVE_INTERVAL)        

# Publish message to MQTT Broker    
mqttc.publish(MQTT_TOPIC,MQTT_MSG)

# Disconnect from MQTT_Broker
mqttc.disconnect()

我只想发布没有payload = {jsondata}格式的JSON数据,如何在每次发布特定主题的数据时删除有效负载?

在日志中它显示了这样的消息--- [payload = {" sepalLength":" 6.4"," sepalWidth":" 3.2"," petalLength":" 4.5"," petalWidth":" 1.5" }]

2 个答案:

答案 0 :(得分:3)

我为你的代码添加了一些修改,然后你可以将json发布为字符串,然后接收字符串并转换为json。

示例代码:

import paho.mqtt.client as mqtt
import json
# Define Variables
MQTT_HOST = "localhost"
MQTT_PORT = 1883
MQTT_KEEPALIVE_INTERVAL = 45
MQTT_TOPIC = "irisPayload"

MQTT_MSG=json.dumps({"sepalLength": "6.4","sepalWidth":  "3.2","petalLength": "4.5","petalWidth":  "1.5"});
# Define on_publish event function
def on_publish(client, userdata, mid):
    print "Message Published..."

def on_connect(client, userdata, flags, rc):
    client.subscribe(MQTT_TOPIC)
    client.publish(MQTT_TOPIC, MQTT_MSG)

def on_message(client, userdata, msg):
    print(msg.topic)
    print(msg.payload) # <- do you mean this payload = {...} ?
    payload = json.loads(msg.payload) # you can use json.loads to convert string to json
    print(payload['sepalWidth']) # then you can check the value
    client.disconnect() # Got message then disconnect

# Initiate MQTT Client
mqttc = mqtt.Client()

# Register publish callback function
mqttc.on_publish = on_publish
mqttc.on_connect = on_connect
mqttc.on_message = on_message

# Connect with MQTT Broker
mqttc.connect(MQTT_HOST, MQTT_PORT, MQTT_KEEPALIVE_INTERVAL)

# Loop forever
mqttc.loop_forever()

答案 1 :(得分:0)

data = {"sepalLength": "6.4","sepalWidth":  "3.2","petalLength": "4.5","petalWidth":  "1.5"}
print json.dumps(data)

打印:

  

{“sepalLength”:“6.4”,“sepalWidth”:“3.2”,“petalLength”:   “4.5”,“petalWidth”:“1.5”}

  

payload = {“sepalLength”:“6.4”,“sepalWidth”:“3.2”,“petalLength”:   “4.5”,“petalWidth”:“1.5”}

你还有一个描述有效负载的操纵字符串 将不需要的密钥添加到msg