Vitor Figueredo
Vitor Figueredo

Reputation: 629

How to read and write multiple related JSON structures in a single file on Python?

I've written a Python script to randomly create a JSON structure containing a student and a grade. The script to create each student and its final grade is:

import json
for i in range(1000):
    finalMedia = {"name":"name", "media":media}
    json.dump(finalMedia, open("xtext.txt",'w'))
    txt.write("\n")

Resulting in a file like this:

...
{"media": 7, "nome": "Bernardo"}
{"media": 7, "nome": "Isadora"}
{"media": 7, "nome": "Pedro"}
{"media": 9, "nome": "Agatha"}
...

When it comes to reading, I wrote another script that also uses the JSON module:

import json
data = json.load(open("xtext.txt"))
print data

I was expecting the whole file data, but instead, I'm getting the following error: Extra data: line 2 column 1 - line 1001 column 1 (char 32 - 31997)

At first, I thought the error was the resulting of breaking the lines. I've decided to remove the txt.write("\n") but after that, I was still getting the same error. Then, I've tried to change txt.write("\n") to txt.write(",") but that didn't work either. So the error must be on my reading. Is there something I have to do with JSON module or it's indeed the way I'm writing my file?

Upvotes: 0

Views: 434

Answers (1)

Joran Beasley
Joran Beasley

Reputation: 113978

data = map(json.loads,open("xtext.txt"))

each line is a json structure ... but when together as a single file thats not valid json

although really you should just write the json.dump once

medias = [{"name":"name", "media":media} for name,media in all_media]
json.dump(medias,open("xtext.txt","wb")) 

Upvotes: 3

Related Questions