There is a list with an internal dictionary:

[ { "users":[{ "name":"Joe", "date":"01.01.2000", "city":"Nevada" }] } ] 

How to add data ("name", "date", "city") to the users dictionary?

I tried this:

 def write_to_json(name,date,city): with open('user_info.json','w') as jf: jf_file = json.load('user_info.json') jf_target = jf_file[0]['users'] user_info = {'name':name,'date':date,'city':city} dump_info = jf_target.append(user_info) json.dump(dump_info,jf) info = input("Name, date (dmy), city: ").split() name = info[0] date = info[1] city = info[2] write_to_json(name,date,city) 

But the data is written outside the dictionary of the main list.

  • d["users"] is not a dictionary — it is a list that contains a dictionary. - jfs

1 answer 1

append adds an element to the list, but does not return a list, i.e. instead

 dump_info = jf_target.append(user_info) 

just write

 jf_target.append(user_info) 

and when writing to a json file, use

 json.dump(jf_file,jf). 

Also confuses the line jf_file = json.load('user_info.json') , it is possible to use a non-standard json module, since otherwise, load would not ask for the file name, but an object with the .read method.

Total such code:

 import json def write_to_json(name, date, city): with open('test.json','r') as jfr: jf_file = json.load(jfr) with open('test.json','w') as jf: jf_target = jf_file[0]['users'] user_info = {'name': name, 'date': date, 'city': city} jf_target.append(user_info) json.dump(jf_file, jf, indent=4) write_to_json('foo', 'bar', 'baz') 

From the document:

 [{ "users" : [{ "name" : "Joe", "date" : "01.01.2000", "city" : "Nevada" } ] } ] 

does:

 [{ "users" : [{ "date" : "01.01.2000", "city" : "Nevada", "name" : "Joe" }, { "date" : "bar", "city" : "baz", "name" : "foo" } ] } ] 
  • First, it overwrites the file, deleting old data. Mode "a" (add) does not fit. But I need to add data to it. Secondly, I need to update one file, and not overwrite from another. - CockLobster
  • In the example, two files were used, solely for debugging convenience (in order not to restore the contents of the source file every time after launch), but nothing prevents you from using the same file (for example, first open to read, read, then open to write, write) . Updated the answer. - Vladimir Gamalyan