Modifying JSON Key Values In Python
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 furthe
Solution 1:
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()
Solution 2:
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()
Post a Comment for "Modifying JSON Key Values In Python"