Python脚本挂在json.loads()上

时间:2019-06-13 03:55:55

标签: python json raspberry-pi3

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

这是在raspberryPi 3,带grovepi板的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.

1 个答案:

答案 0 :(得分:0)

所以我安装了simplejson并运行了相同的代码 导入simplejson为json

现在可以使用了!

不确定Python随附的json出了什么问题,但至少我可以完成我的任务。我认为要解决此问题,我将不得不重新安装Python?