0
votes

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.

1
Do you really have empty lines in between each line? And is your for loop block really not indented inside the with block? Because after removing the empty lines and fixing the indentation, your code seems to work: i.stack.imgur.com/2xREE.png - Gino Mempin
"doesn't seem to be working" is not a concrete error description. What does it do? What do you see? Please provide a minimal reproducible example and read How to Ask. - Ulrich Eckhardt

1 Answers

0
votes

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'}]