-1

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?

bgrow11
  • 31
  • 8
  • 1
    You're trying to add a user to the list/array, yes? Then why are you using update on the root dictionary/object? @CharlesDuffy wouldn't that call update on a list? – jonrsharpe Oct 28 '17 at 18:02
  • BTW, this method for updating a data file in place is generally speaking likely to cause you trouble. If your program gets interrupted after the `with open()` and before the `json.dump()` is complete and its output is flushed, you've lost all your data. – Charles Duffy Oct 28 '17 at 18:03
  • @jonrsharpe, ahh, right. Not a well-chosen data structure for the operation at hand. (What's updating a list with a dict with an identical key to one of its members *supposed to do* anyhow?) – Charles Duffy Oct 28 '17 at 18:04
  • @bgrow11, ...anyhow, perhaps instead of having a list of dictionaries you should have *just one* dictionary, with the username as the key and a dictionary of data about that user as the value. Then you don't have to figure out what your code is supposed to do in a situation where there are multiple list entries with the same `name`, or to which specific dict an `update` or similar operation is supposed to apply. – Charles Duffy Oct 28 '17 at 18:06
  • **json.dump(data, f, indent=2)** – Anton vBR Oct 28 '17 at 21:28
  • Possible duplicate of [How to prettyprint a JSON file?](https://stackoverflow.com/questions/12943819/how-to-prettyprint-a-json-file) – Anton vBR Oct 28 '17 at 21:30

1 Answers1

0

just replace 'w' with 'a' like below

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