简体   繁体   中英

Python2 vs Python3 - parsing JSON

I try to read MQTT messages using Python. For debugging purposes, I reduced the program at the minimum.

import paho.mqtt.client as mqtt
import json

def on_connect(client, userdata, flags, rc):
    print("Connected with code  " + str(rc))
    client.subscribe("temperature")

def on_message(client, userdata, message):
    if message.topic == "temperature":
        print("New message received")        
        dhtreadings_json = json.loads(message.payload)
        temperature = dhtreadings_json['temperature']
        print(temperature)

mqttc = mqtt.Client()
mqttc.username_pw_set("user","password")                  
mqttc.on_connect = on_connect
mqttc.on_message = on_message
mqttc.connect("192.168.1.133",1883,60)
mqttc.loop_forever()

Under Python 2, everything works fine:

Python2 中的输出

Under Python3, I got the connection established message and I am informed that a new message was received and this is all. More than this no other output after:

Python3 中的输出

Environment: Latest version of Raspbian on Raspberry Pi 3B+

As suggested, I replaced to print ("New message received", message.payload). The message.payload is the same in Python2 and Python3.

Python2:

在 Python2 中打印 message.payload

Python3:

在 Python3 中打印 message.payload

Thank you!

This will be because with Python3 the message.payload is a byte array and with Python2 it's a string. (this can be seen in the images you posted because the Python3 strings are proceeded with b'... )

The change is to move closer to the MQTT spec which treats all MQTT payloads as just a collection bytes and also not making any assumptions about what character set should be used to covert the payload to a string.

The following should work with Python3 (assuming the initial json is utf-8 encoded)

dhtreadings_json = json.loads(message.payload.decode("utf-8"))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM