0

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?

1 Answer 1

3
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")) 
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for your quick answer, i tried your first solution, using "map" and python returns this error: AttributeError: 'str' object has no attribute 'read'. I'm going to try your 2nd solution. Thank you again.
@VitorFigueredo whoops should have been json.loads since its a string now not a file (fixed)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.