【发布时间】:2022-01-22 18:42:26
【问题描述】:
想法:
我想将 JSON 对象添加到现有 JSON 文件,但不覆盖文件中的现有数据。
uid-003 对象应该在现有的 uid-xxx 条目之后从属于 uID。
问题:
没有任何解决方案可以正常工作。 append() 方法也返回错误:AttributeError: 'dict' object has no attribute 'append'。
当前代码
Python代码:
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 文件:
{
"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
}
}
}
}
【问题讨论】:
标签: python json python-3.x file