Python 3 Paho-MQTT发布/订阅的JSON消息无法解析

时间:2018-11-16 08:58:49

标签: python json python-3.x mqtt paho

菜鸟在这里。

我有一个简单的python代码,该代码应该订阅一个主题,并使用MQTT协议将JSON有效内容发布到同一主题。但是由于某种原因,我无法将有效载荷作为JSON加载!

我在这里做什么错了?

# -*- coding: utf-8 -*-
import paho.mqtt.client as mqtt
import json
mqtt_broker      = '192.168.1.111'
mqtt_topic_one   = 'mqtt_topic/tops_one'
mqtt_topic_two   = 'mqtt_topic/tops_two'

json_data_1      = '''{
    "this_json": "info",
    "data": {
        "multi_keyval": {
            "1": "1",
            "5": "5",
            "15": "15"
        },
        "single_keyval": {
            "single_key": "200"
        }
    }
}'''


def pass_to_func_and_pub(data_to_pub):
    print(data_to_pub)                # --------> This PRINTS
    print(json.loads(data_to_pub))    # --------> This DOES NOT PRINT

    # The following two lines don't work either.
    unpacked_json = json.loads(data_to_pub)
    client.publish(mqtt_topic_two, unpacked_json['this_json'])


def on_connect(client, userdata, flags, rc):
    client.subscribe(mqtt_topic_one)
    client.publish(mqtt_topic_one, json_data_1)


def on_message(client, userdata, msg):
    pass_to_func_and_pub(str(msg.payload))

client = mqtt.Client()

client.on_connect = on_connect
client.on_message = on_message

client.connect(mqtt_broker)
try:
    client.loop_forever()
except KeyboardInterrupt:
    client.disconnect()
    print('MQTT client disconnected, exiting now.')

1 个答案:

答案 0 :(得分:4)

这里有两个问题。

1。异常处理

您没有处理异常(我猜Paho实际上会在处理程序中忽略它们,以使客户端保持活动状态)。这意味着当在json.loads(data_to_pub)中抛出异常 时,您永远不会看到此异常,但是由于没有本地except块而退出了函数。

改进版本

def pass_to_func_and_pub(data_to_pub):
    print("Raw data: ", data_to_pub)
    try:
        unpacked_json = json.loads(data_to_pub)
    except Exception as e:
        print("Couldn't parse raw data: %s" % data_to_pub, e)
    else:
        print("JSON:", unpacked_json)
        client.publish(mqtt_topic_two, unpacked_json['this_json'])

等等,有什么例外吗?

运行此改进版本,我们现在可以看到:

Couldn't parse raw data: b'{\n "this_json": "info",\n "data": {\n "multi_keyval": {\n "1": "1",\n "5": "5",\n "15": "15"\n },\n "single_keyval": {\n "single_key": "200"\n }\n }\n}' Expecting value: line 1 column 1 (char 0)

嗯,b'在那做什么? ...

2。编码问题

基本上,您的问题归结为一行

def on_message(client, userdata, msg):
    pass_to_func_and_pub(str(msg.payload))

通过在str的{​​{1}}(在Python 3中是payload对象)的MqttMessage上调用bytes,您将获得这些字节的字符串化版本,例如b'foobar'

这个b当然现在使它成为无效的JSON,因此Expecting value: line 1 column 1 (char 0) ...

固定版本

请勿致电strJson.loads can handle bytes too。所以:

def on_message(client, userdata, msg):
    pass_to_func_and_pub(msg.payload)

或者,假设使用utf-8编码,我们可以更明确地做到这一点(我更喜欢在字符串中工作):

def on_message(client, userdata, msg):
    pass_to_func_and_pub(msg.payload.decode('utf-8'))

希望有帮助!