How i add another list in json python

Viewed 38

my json file :

{
"ali":{"name":"ali","age":23,"email":"his email"},
"joe":{"name":"joe","age":55,"email":"his email"}
}

And my code

name=input("name:")
age=input("age: ")
email=input("email:")
 list={}
list[name]={"name":name,"age":age,"email":email}
data=json.dumps(list)
with open ('info.json','a') as f:
  f.write(data)

i need method to append anather one (another name)to the json file

any idea?

1 Answers

To update an existing json file you need to read the entire file, make adjustments and write the whole lot back again:

with open ('info.json','r') as f:
    data = json.load(f)

name = input("name:")
age = input("age: ")
email = input("email:")

data[name] = {"name":name, "age":age, "email":email}

with open ('info.json','w') as f:
     json.dump(data, f)

By the way, there are no lists involved here, just nested dictionaries.

Also, if the user enters a duplicate name, then this code will overwrite the one in the file with updated data. This may, or may not, be what you want.

Related