How to read multiple JSON objects in a single file?

898 views Asked by At

I want to read multiple JSON objects from a single file imported from local dir. So far this is my simple work:

Data:

[{
    "uuid": "6f476e26",
    "created": "2018-09-26T06:57:04.142232",
    "creator": "admin"

}, {
    "uuid": "11d1e78a",
    "created": "2019-09-21T11:19:39.845876",
    "creator": "admin"
}]

Code:

import json
with open('/home/data.json') as f:
    for line in f:
        data = json.load(f)

Error:

 File "/usr/lib64/python3.8/json/decoder.py", line 340, in decode
    raise JSONDecodeError("Extra data", s, end)
json.decoder.JSONDecodeError: Extra data: line 1 column 8 (char 7)

My question is similar to Loading and parsing a JSON file with multiple JSON objects and I've tried it however same issue appears. What should I do to solve this issue?

1

There are 1 answers

0
DeepSpace On BEST ANSWER
for line in f:
    data = json.load(f)

This makes no sense. You are trying to parse the file over and over again, as many times as the number of lines in the file. This is more problematic than it sounds since f is exhausted after the first call to json.load(f).

You don't need the loop, just pass f to json.load:

with open('/home/data.json') as f:
    data = json.load(f)
print(data)

outputs

 [{'uuid': '6f476e26', 'created': '2018-09-26T06:57:04.142232', 'creator': 'admin'},
  {'uuid': '11d1e78a', 'created': '2019-09-21T11:19:39.845876', 'creator': 'admin'}]

Now you can loop over data or directly access a specific index, ie data[0] or data[1].