3

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()

2 Answers 2

2

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

Comments

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()

Comments

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.