Reputation: 31
I am trying to load a JSON file and change specific key values then save the updated entries to a new file. This JSON file has many entries with the same format. This is my furthest attempt before coming here, however it does not save the new values.
What am I missing?
#!/usr/bin/python
import simplejson as json
import names
in_file = open('Names.json', 'r')
out_file = open('Names_new.json','w')
data_file = in_file.read()
data = json.loads(data_file)
for x in data:
nickname = x['nickname']
newname = names.get_first_name()
nickname = newname
out_file.write(json.dumps(data))
out_file.close()
Upvotes: 3
Views: 18660
Reputation: 3437
The problem is that you didn't change x['nickname'] when you wanted to assign newname
to it. Instead, you only modified the variable nickname
.
Try assigning the x['nickname']
directly:
for x in data:
x['nickname'] = names.get_first_name()
Upvotes: 2
Reputation: 1650
You are just dumping old JSON data again into a new file without modifying its contents.
Instead, you should change the contents of the file with newname
:
#!/usr/bin/python
import simplejson as json
import names
in_file = open('Names.json', 'r')
out_file = open('Names_new.json','w')
data_file = in_file.read()
data = json.loads(data_file)
for x in data:
newname = names.get_first_name()
x['nickname'] = newname
out_file.write(json.dumps(data))
out_file.close()
Upvotes: 2