Saturday, July 23, 2022

[FIXED] How can i add some element into json file using python?

Issue

this is json {"name": ["Juan", "Alex"]}. how can i add something to "name", using python? thanks in advance for your reply. This is my code, he is don't work :(

import json

enteredString = str(input())
json_file = 'list_of_workers.json'
data = json.load(open(json_file, "rb"))
data['name'].append(enteredString)
json.dump(data, open(json_file, "wb"))

Solution

import json

enteredString = str(input())
json_file = 'list_of_workers.json' 
data = json.load(open(json_file, "rb"))
data['name'].append(enteredString)
newdata = json.dumps(data, indent=4, sort_keys=True)  
with open(json_file, 'w') as f:   
    f.write(newdata)


Answered By - Ari Abimanyu
Answer Checked By - Senaida (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.