NGuyen NGuyen - 3 months ago 14
JSON Question

Python 3: How to read file json into list of dictionary?

I have file with Json format:

{"uid": 2, "user": 1}
{"uid": 2, "user": 1}
{"uid": 2, "user": 1}


When i use following code, it show an error:

raise JSONDecodeError("Extra data", s, end)
json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 22)

with open('E:/list.txt','r') as target:
my_list = json.load(target)


How to convert content of my file into list of dictionary ? Thank you

BPL BPL
Answer

It's not loading your content basically because it's not a valid json format, try this script:

import json

try:
    file_content = """{"uid": 2, "user": 1}
    {"uid": 2, "user": 1}
    {"uid": 2, "user": 1}"""

    json.loads(file)
except Exception as e:
    print("This is not JSON!")

print('-' * 80)
file_content = """[{"uid": 2, "user": 1},
{"uid": 2, "user": 1},
{"uid": 2, "user": 1}]"""

print(json.loads(file_content))

The result will be:

This is not JSON!
--------------------------------------------------------------------------------
[{'user': 1, 'uid': 2}, {'user': 1, 'uid': 2}, {'user': 1, 'uid': 2}]

Proving that if if you wrap your dictionary into brackets and separate the items with commas the json will be parsed correctly

Of course, If you don't want to tweak your file at all, you can do something like this to create your output:

import json

file_content = """{"uid": 2, "user": 1}


{"uid": 2, "user": 1}


{"uid": 2, "user": 1}

"""

output = [json.loads(line)
          for line in file_content.split("\n") if line.strip() != ""]
print(output)