Home > database >  How can i add some element into json file using python?
How can i add some element into json file using python?

Time:12-26

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



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

CodePudding user response:

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)
  • Related