我试图读取串行端口(使用arduino),然后将输入转换为字典,我已经在arduino代码中生成了字符串,以便它与我可以根据其他线程找到的样子相匹配。
receive_string = ser.readline().decode('utf-8', 'replace')
print(receive_string)
给出:{'value_left': 10, 'target_left': 20, 'u_left': 10.30, 'value_right': 11, 'target_right': 21, 'u_right': 11.30}
但是,当我尝试使用 json.loads 将其转换为字典时:
data = json.loads(receive_string)
我得到错误:
Traceback (most recent call last):
File "send_and_rcv_int.py", line 36, in <module>
data = json.loads(receive_string)
File "/Users/jakobvinkas/opt/anaconda3/lib/python3.8/json/__init__.py", line 357, in loads
return _default_decoder.decode(s)
File "/Users/jakobvinkas/opt/anaconda3/lib/python3.8/json/decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/Users/jakobvinkas/opt/anaconda3/lib/python3.8/json/decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
我错过了什么?
我试图不解码readline()
并使用"
instaed'
但没有任何效果。
—————————编辑—————————</p>
起作用的是一种丑陋的修复:
receive_string = ser.readline().decode('utf-8', 'replace')
try:
data = json.loads(receive_string)
print(data)
except:
data = {}
问题是第一个ser.readline()
由于某种原因什么都不返回,导致错误。