gpt4 book ai didi

Python 脚本卡在 json.loads() 上

转载 作者:太空宇宙 更新时间:2023-11-03 20:46:21 24 4
gpt4 key购买 nike

我正在尝试为一个类运行一个脚本,该类采用 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.

最佳答案

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

现在可以了!

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

关于Python 脚本卡在 json.loads() 上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56573175/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com