NGuyen
NGuyen

Reputation: 275

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

Upvotes: 1

Views: 6374

Answers (3)

levi
levi

Reputation: 22697

Your file is not a JSON, its a list of JSON.

with open(filec , 'r') as f:
    list = list(map(json.loads, f))

Upvotes: 3

rafaelc
rafaelc

Reputation: 59274

You'll have to iterate, because json.load won't do that automatically.
So should have something like this

for line in file:
    json_obj = json.loads(line)
    my_list.append(json_obj)

Upvotes: 1

BPL
BPL

Reputation: 9863

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)

Upvotes: 4

Related Questions