Issue
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?
Solution
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)
Answered By - Woodford
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.