The idea:
I want to add a JSON object to an existing JSON file, but not overwrite the existing data in the file.
The uid-003 object should come subordinate to uID after the existing uid-xxx entries.
The problem:
No solution approach works as it should. The append() approach also returns the error: AttributeError: 'dict' object has no attribute 'append'.
The current code
Python code:
user = {
"uid-003": {
"username": "username-3",
"pinned": "pinned",
"created": {
"date": "DD/MM/YYYY",
"time": "HH:MM:SS"
},
"verified": {
"checked": False
}
}
}
with open("path/to/json", "r+") as file:
data = json.load(file)
temp = data['uID']
temp.append(user)
json.dump(data, file)
JSON file:
{
"uID": {
"uid-001": {
"username": "username-1",
"pinned": false,
"created": {
"date": "20-12-2021",
"time": "21:13:39"
},
"verified": {
"checked": false
}
},
"uid-002": {
"username": "username-2",
"pinned": true,
"created": {
"date": "20-12-2021",
"time": "21:13:39"
},
"verified": {
"checked": false
}
}
}
}
>Solution :
All you need to do is add your user dictionary to the existing ‘uID’ key. If you update a file that’s been opened with r+ and you’re increasing the amount of data in the file, you’ll need to seek to the beginning before writing. This should help:
import json
THE_FILE = 'the_file.json'
user = {
"uid-003": {
"username": "username-3",
"pinned": "pinned",
"created": {
"date": "DD/MM/YYYY",
"time": "HH:MM:SS"
},
"verified": {
"checked": False
}
}
}
with open(THE_FILE, 'r+') as jfile:
j = json.load(jfile)
for k, v in user.items():
j['uID'][k] = v
jfile.seek(0)
json.dump(j, jfile, indent=4)
Note: The iteration over user.items() isn’t really necessary in this case but serves to show how you might use this pattern when user contains more dictionaries than just the one in your example