我正在尝试通过串口读取arduino中的数据,该序列发送一个名称和值为6个传感器的JSON字符串。
我已经检查了JSON验证器中的字符串是否有效。问题是我在尝试从JSON字符串中获取字典时收到错误。
import json
import serial
import Sensor
s = serial.Serial('COM3',9600)
while True:
m = s.readline()
x = m.decode('UTF-8').rstrip("\n")
b = json.loads(x)
print(b['list'])
{"list":[{"name":"A0","value":"17"},{"name":"A1","value":"39"},
{"name":"A2","value":"13"},{"name":"A3","value":"48"},
{"name":"A4","value":"10"},{"name":"A5","value":"42"}]}
错误
Traceback (most recent call last):
File "C:/Users/andrei_vlad/PycharmProjects/untitled/serial_comm.py", line 9, in <module>
b = json.loads(x)
File "C:\Python34\lib\json\__init__.py", line 318, in loads
return _default_decoder.decode(s)
File "C:\Python34\lib\json\decoder.py", line 343, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Python34\lib\json\decoder.py", line 361, in raw_decode
raise ValueError(errmsg("Expecting value", s, err.value)) from None
ValueError: Expecting value: line 1 column 1 (char 0)
更新: 我解决了这个问题。解码在字符串之前和之后添加''。我刚刚使用x [1:-1]它现在有效。我还有另一个字符串,它在readline中发送,以通知连接已开始。
答案 0 :(得分:0)
解码在字符串的开头和结尾添加“'”,因此我必须使用x = x[1:-1]
删除这两个字符
解决方案:
import json
import serial
import Sensor
s = serial.Serial('COM3',9600)
m = s.readline()
print([m])
x =m.decode().strip('\n\r')
x = x[1:-1]
x = json.loads(x)
print(x['list'])