简体   繁体   中英

Adding values to JSON file in python

I currently have a son file created called "newsuser.json". I am trying to get a users name to be saved to the son file each time a new user is added. I can currently get a user to be saved, but when another user is added the previous user is overwritten, resulting in only having one user stored.

I am trying to get me JSON file to look like this:

{  
   "users":[  
      {  
         "name":"test1"
      },
      {  
         "name":"test2"
      }
   ]
}

Instead my output looks like:

{"name": "test1"}

Here is my code for creating a JSON object and saving to "newsuser.json"

import json

  userName = form.getvalue('userName')
    newDict = {"name": "test1"}

    with open("cgi-bin/newsuser.json") as f:
        data = json.load(f)

    data.update(newDict)

    with open("cgi-bin/newsuser.json", "w") as f:
        json.dump(data, f)

Does anyone have ideas how I can get a JSON file to print my objects under "user" and not overwrite each entry?

just replace 'w' with 'a' like below

with open("cgi-bin/newsuser.json", "a") as f:
    json.dump(data, f)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM