Vitor Figueredo Vitor Figueredo - 3 months ago 12
JSON Question

Trying to write and read multiple lines on a JSON File on python

I'm writing a random script to make a student name be linked with a grade on a dictionary, it's simple, for writing on a file, i'm using a JSON module:

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


For reading i wrote a script that also uses the JSON module:

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


But i get the error: "Extra data: line 2 column 1 - line 1001 column 1 (char 32 - 31997)"

I already tried removing the txt.write("\n") and tried changing to: txt.write(","). Is there something i have to do with JSON module or it's just the way i'm writing the file?

Answer
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"))