I've been working on a piece of cod that needs to add to the end of a dict. (the dict being some JSON) The main issue I have been having is that it's not adding to the dictionary the way I wish.
Here is my code for adding to the dict:
with open("data.json", "r") as read_file:
data = json.load(read_file)
data['user'] = str(data['user']) + "username: " + a
with open("data.json", 'w') as f:
json.dump(data, f)
Here is the JSON:
{"user": [
{"username": "a", "data": "a"},
{"username": "b", "data": "b"},
{"username": "c", "data": "c"}
]}
The result I expected:
{"user": [
{"username": "a", "data": "a"},
{"username": "b", "data": "b"},
{"username": "c", "data": "c"},
{"username": "d"}
]}
The result I got:
{"user": [
{"username": "a", "data": "a"},
{"username": "b", "data": "b"},
{"username": "c", "data": "c"}
]}
{"username": "d"}
I think it's how i'm formatting the data['user'] = str(data['user']) + "username: " + a line, but I am having issues coming up with how to format it otherwise. Thanks for any answers!
Edit: here was the complete working code:
with open("data.json", "r") as read_file:
data = json.load(read_file)
data['user'].append({"username": a})
with open("data.json", 'w') as f:
json.dump(data, f)