0

Im trying to read the serial port (using arduino) and then convert the input to a dictionary, I have generated the string in the arduino code so that it matches what I could find what it should look like according to other threads.

receive_string = ser.readline().decode('utf-8', 'replace')
print(receive_string)

Gives: {'value_left': 10, 'target_left': 20, 'u_left': 10.30, 'value_right': 11, 'target_right': 21, 'u_right': 11.30}

However when I try to convert it to a dict using json.loads:

data = json.loads(receive_string)

I get the error:

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)

What am I missing?

I have tried to not decode the readline() and to use " instaed of ' but nothing works.

———————— edit ————————

What worked was sort of an ugly fix:

receive_string = ser.readline().decode('utf-8', 'replace')
    try:
        data = json.loads(receive_string)
        print(data)
    except:
        data = {}

The problem was that the first ser.readline() return nothing for some reason, causing the error.

1

2 Answers 2

0

receive_string is type string so you need to convert string to dict. Try this :

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

If this does not work then check : How convert a JSON string to Dictionary in Python?

Sign up to request clarification or add additional context in comments.

Comments

-1

Try to use eval() instead of json.loads()

data = eval(receive_string)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.