[英]Append list in JSON file with Python
I'm trying to append a list with new names in a json file. 我正在尝试在json文件中追加具有新名称的列表。
JSON structure: JSON结构:
{
"users": [
"User1",
"User2",
"User3"
]
}
I have tried this: 我已经试过了:
with open('data/users.json', 'r') as json_file:
json_data = json.load(json_file)
user_list = json_data["users"]
with open('data/users.json', 'w') as json_file:
user_list.append(name)
json.dump(user_list, json_file)
But it turns out like this: 但是结果是这样的:
["User1", "User2", "User3", "User4"]
Why and how do I fix it? 为什么以及如何解决?
You need to write the whole data dictionary, not just the list 您需要编写整个数据字典,而不仅仅是列表
with open('data/users.json', 'r') as json_file:
json_data = json.load(json_file)
json_data["users"].append(name)
with open('data/users.json', 'w') as json_file:
json.dump(json_data, json_file)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.