Home > Software design >  How do i get a dictionary appended into a list without overlapping the exitsting dictionary json
How do i get a dictionary appended into a list without overlapping the exitsting dictionary json

Time:11-05

Im writing the code with Python, JSON and flask Ive made a function "make_user():" to take data from my form and insert it into a dictionary:

users_list = []
@app.route("/makeuser", methods=["post"])
def make_user():
    firstname = f.request.form["firstname"]
    lastname = f.request.form["lastname"]
    username = f.request.form["username"]
    password = f.request.form["pwd"]
    mail = f.request.form["email"]
    car = f.request.form["car"]

    res = {
        "firstname" : firstname,
        "lastname" : lastname,
        "username" : username,
        "password" : password,
        "mail" : mail,
        "car" : car
    }

Where the trouble comes is when i try to open my json file, then add the existing dictionaries to the users_list and then append the input from the form, then dump the new list to the json file. This is my try:

file = open("users.json", "r ")
users_list.append(file)

for list_item in users_list:
    users_list.append(res)

json.dump(users_list,file)
file.close

return redirect(url_for("form"))

what i want to have in the json file is a list with list items as dictionarys like so: [{},{},{},{}]

Any ideas to how i fix this?

CodePudding user response:

file = open("users.json", "r ")
users_list.append(file)

file here does not contain the contents of users.json. It's a "handle" to an open file that you can read data from -- or pass to json.load.

for list_item in users_list:
    users_list.append(res)

This bit is nonsensical. Assuming you correctly loaded the contents of users.json this would append res to each element. Not only is that not what you want, it's not possible as each element is a dict.

Since you're replacing the contents of the file you need to open it twice; once for reading and once for writing. You can't append to the file because that will break the structured JSON. Try something like this:

with open("users.json") as file:
    users_list = json.load(file)

users_list.append(res)

with open("users.json", "w") as file:
    json.dump(users_list, file)

CodePudding user response:

You need to load the data from the json file.

with open("users.json", "r") as file:
    try:
        users_list = json.load(file) # This should be your saved json structure
    except json.decoder.JSONDecodeError: # in case your file does not contain valid json or is empty
        users_list = []
if isinstance(users_list, dict): # this can be removed if your top level is a list
    users_list = [users_list]
users_list.append(res) # append to the existing list
with open("users.json", "w") as file:
    json.dump(users_list, file) # dump back to file

Let's say this is what is in your file.

{
    "firstname" : "Martin",
    "lastname" : "Mouse",
    "username" : "mmouse",
    "password" : "hunter9",
    "mail" : "[email protected]",
    "car" : "Lambo"
}

The json module has a convenience function that reads your file from data and parses it into python objects in one step.

users_list = json.load(file)

This is essentially saying:

user_list = {
    "firstname" : "Martin",
    "lastname" : "Mouse",
    "username" : "mmouse",
    "password" : "hunter9",
    "mail" : "[email protected]",
    "car" : "Lambo"
}

The next step is to make sure your top level is a list and if not make it so.

if isinstance(users_list, dict):
    users_list = [users_list]

So now your structure looks like this.

[
    {
        "firstname" : "Martin",
        "lastname" : "Mouse",
        "username" : "mmouse",
        "password" : "hunter9",
        "mail" : "[email protected]",
        "car" : "Lambo"
    }
]

At this point you can append your new entry.

users_list.append(res)

Which is now this.

[
    {
        "firstname" : "Martin",
        "lastname" : "Mouse",
        "username" : "mmouse",
        "password" : "hunter9",
        "mail" : "[email protected]",
        "car" : "Lambo"
    },
    {
        "firstname" : "Darnold",
        "lastname" : "Duck",
        "username" : "dduck",
        "password" : "hunter10",
        "mail" : "[email protected]",
        "car" : "Ferrari"
    }

]

And finally, dump back to file.

with open("users.json", "w") as file:
    json.dump(users_list, file) # dump back to file
  • Related