Skip to content Skip to sidebar Skip to footer

Python: Read In An Array Of Json Objects Using Json.loads()

I have a file data.txt which contains a list of json objects like below: [{'id':'1111','color':['blue'],'length':'120'},{'id':'1112','color':['red'],'length':'130'},{'id':'1112','c

Solution 1:

You're trying to read the string "data.txt". What you want is to open and read the file.

import json

with open('data.txt', 'r') as data_file:
    json_data = data_file.read()

data = json.loads(json_data)

Solution 2:

Try:

data = json.load(open("data.txt", 'r'))

json.loads interprets a string as JSON data, while json.load takes a file object and reads it, then interprets it as JSON.


Solution 3:

You need to open the file for reading and read it. To get the behavior you want:

with open('data.txt', 'r') as f:
    data = json.loads(f.read())

That should give you the json structure you want. Using with keeps you from having to close the file explicitly when you're finished.


Post a Comment for "Python: Read In An Array Of Json Objects Using Json.loads()"