python - 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.
解决方案
所以我安装了 simplejson 并使用 import simplejson as json 运行了相同的代码
现在它起作用了!
不确定 Python 附带的 json 有什么问题,但至少我可以完成我的任务。我在想要解决这个问题,我必须重新安装 Python?
推荐阅读
- c++ - 在共享库中隐藏派生类的符号
- r - 如何使用 R 包“gtsummary”在汇总表中添加卡方效应大小 Cramer's V?
- docker - Microk8s 无法启动本地 docker 镜像
- java - ikvm openjdk 核心 v8.1.7195 缺失
- tensorflow - [Apple M1]:我没有为与节点 {{node RngReadAndSkip}} 兼容的“GPU”设备注册的“RngReadAndSkip”OpKernel。注册:设备='CPU'
- android - Android 12 Pending Intent Immutable 标志在 API 23 下不可用
- mysql - 如何创建也匹配空字段或空字段的唯一键?
- python - ValueError:具有多个元素的数组的真值不明确。使用 a.any() 或 a.all()。如何使用它?
- python - 从 pandas 数据框中访问数据
- python - Python:如何定义一个行为像函数的类?