Reputation: 23
I am doing an assignment on python and I was trying to dump a dictionary that contains a list of another dictionary into JSON. However, upon running the data, it made an error:
File "D:\Users\XXXXX\Anaconda2\lib\json\decoder.py", line 367, in decode raise ValueError(errmsg("Extra data", s, end, len(s))) ValueError: Extra data: line 1 column 76 - line 1 column 1434 (char 75 - 1433)
Here is the code snippet on the JSON writer:
def savelist(self):
data={}
f = open('partjson.txt','w')
for i in range(self.datacount):
data.setdefault("data",[]).append({'name':self.namelist[i], 'numid':str(self.numidlist[i]), 'height':str(self.heightlist[i]), 'length':str(self.lengthlist[i])})
json.dump(data,f)
f.close()
The data file outputted is not as intended since the dictionary "data" is outputted multiple time instead of only once at the beginning.
{"data": [{"length": "3", "numid": "1", "name": "first", "height": "2.0"}]}{"data": [{"length": "3", "numid": "1", "name": "first", "height": "2.0"}, {"length": "4", "numid": "2", "name": "second", "height": "3.0"}]}
Could you please tell me what is wrong with my method? Thank you
Upvotes: 0
Views: 619
Reputation: 26
You misplaced the indentation for the json.dump(data, f)
. The data.setdefault
is called on every loop, creating your so-called "data" dictionary entry. This creates the error. The code should be:
def savelist(self):
data={}
f = open('partjson.txt','w')
for i in range(self.datacount):
data.setdefault("data",[]).append({'name':self.namelist[i], 'numid':str(self.numidlist[i]), 'height':str(self.heightlist[i]), 'length':str(self.lengthlist[i])})
json.dump(data,f)
f.close()
Upvotes: 1