0

我试图读取串行端口(使用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()由于某种原因什么都不返回,导致错误。

4

2 回答 2

0

receive_string 是字符串类型,因此您需要将字符串转换为 dict。尝试这个 :

import json
import ast
out="{'value_left': 10, 'target_left': 20, 'u_left': 10.30, 'value_right': 11, 'target_right': 21, 'u_right': 11.30}" # given dict string
res = ast.literal_eval(out) # converting dict string to dict
print(json.dumps(res)) # converting dict to json

如果这不起作用,请检查:如何在 Python 中将 JSON 字符串转换为字典?

于 2020-12-08T13:57:21.167 回答
-1

尝试使用eval()而不是json.loads()

data = eval(receive_string)
于 2020-12-08T14:08:16.710 回答