首页 > 解决方案 > Python 脚本挂在 json.loads() 上

问题描述

我正在尝试为一个类运行一个脚本,该类需要一个 JSON 有效负载来打开或关闭 LED。我能够获取有效负载并使用 print() 打印出主题和有效负载。但是,在运行脚本时,它会挂在 json.loads() 上。任何帮助,将不胜感激。

这是在带有 grovepi 板和 led 的 raspberryPi 3、python 3.5.3 上。我运行了 grovepi 附带的 led_fade 脚本,所以我知道硬件工作正常。

import time
import grovepi
import paho.mqtt.client as mqtt
import json


# Connect the LED to digital port D5
led = 5

# Set the blue LED pin to output mode
grovepi.pinMode(led,"OUTPUT")
time.sleep(1)

def on_connect(client, userdata, flags, rc):
"""Called each time the client connects to the message broker
:param client: The client object making the connection
:param userdata: Arbitrary context specified by the user program
:param flags: Response flags sent by the message broker
:param rc: the connection result
:return: None
"""
# subscribe to the LEDs topic when connected
client.subscribe("SNHU/IT697/leds")


def on_message(client, userdata, msg):
"""Called for each message received
:param client: The client object making the connection
:param userdata: Arbitrary context specified by the user program
:param msg: The message from the MQTT broker
:return: None
"""
print(msg.topic, msg.payload)
payload = json.loads(msg.payload)
# the legal values for analogWrite are 0-255
grovepi.analogWrite(led, payload['blue'])

json payload that I am sending is:
mosquitto_pub -d -t "SNHU/IT697/leds" -m {\"blue\":0}

When running the script I get the results of the print(msg.topic, msg.payload):  SNHU/IT697/leds b'{"blue":0}'

I should see the led turn off if it receives a '0' value, but I believe that the script gets hung up on the payload=json.loads(msg.payload) statement.

标签: pythonjsonraspberry-pi3

解决方案


所以我安装了 simplejson 并使用 import simplejson as json 运行了相同的代码

现在它起作用了!

不确定 Python 附带的 json 有什么问题,但至少我可以完成我的任务。我在想要解决这个问题,我必须重新安装 Python?


推荐阅读