json.load

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
Post Reply
Karebo
Posts: 2
Joined: Tue Sep 28, 2021 6:10 am

json.load

Post by Karebo » Tue Oct 05, 2021 7:27 am

json.loads(x) works, but json.load(frr) doesn't work. Data are the same.
Any idea?

>>> frr = open("jsdata.json", "r")
>>> x = frr.read()
>>> json.loads(x)
{'value_d1': [0, 1, 2, 3, 4, 5, 6, 7, 8], 'dtime': '00.00.00 00:00', 'value_d2': [0, 1, 2, 3, 4, 5, 6, 7,
8], 'device_2': 'Humidity', 'device_1': 'Temperature'}
>>> fr = json.load(frr)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: syntax error in JSON

pagano.paganino
Posts: 89
Joined: Fri Sep 11, 2015 10:47 pm
Location: Italy

Re: json.load

Post by pagano.paganino » Tue Oct 05, 2021 9:02 am

Hi Karebo Try with:

Code: Select all

with open("jsdata.json", "r") as frr:
    x = frr.read()
    json.loads(x)
and with:

Code: Select all

with open("jsdata.json", "r") as frr:
    json.load(frr)
the problem is in the position of the cursor in the file.

If you use frr.read() the cursor is positioned at the end of the file and using json.load(frr) there is nothing else to read.

using the with you ensure a correct reading of the file and closing.

If you want to use the same FD then use the seek method.

Karebo
Posts: 2
Joined: Tue Sep 28, 2021 6:10 am

Re: json.load

Post by Karebo » Tue Oct 05, 2021 11:22 am

Thanks. My live will be better now :D

Post Reply