Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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"}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{"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'}]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading