Loading JSON-L File

I have been trying to load the file in the format ‘.json’ with multiple lines i.e. it has the following format(arbitrary data):

data.json :

{"John" : "doe", "Age" : "Unknown"}

{"kat" : "doe", "Age" : "Unknown"}

{"Brian" : "doe", "Age" : "Known"}

I have tried the following lines of code which doesn’t seem to be working.

dt = []
with open("data.json") as file:
for line in file.readlines():
    temp = json.loads(line)
    dt.append(temp)
print(dt)

I keep getting an empty list.

>Solution :

Firstly, a json file can’t have multiple objects without being inside of a list.
So you would have to firstly find a way to make the objects in the file within a list:

[
    {"John" : "doe", "Age" : "Unknown"},
    {"kat" : "doe", "Age" : "Unknown"},
    {"Brian" : "doe", "Age" : "Known"}
]

Then your python wasn’t too far off. Something like this would work:

dt = []
with open('data.json') as file:
    for object in json.load(f):
        dt.append(object)
    file.close()

print(dt) # Output: [{'John': 'doe', 'Age': 'Unknown'}, {'kat': 'doe', 'Age': 'Unknown'}, {'Brian': 'doe', 'Age': 'Known'}]

Leave a Reply