Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/303.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
用Python在JSON文件中追加列表_Python_Json_Python 3.x - Fatal编程技术网

用Python在JSON文件中追加列表

用Python在JSON文件中追加列表,python,json,python-3.x,Python,Json,Python 3.x,我试图在json文件中添加一个带有新名称的列表 JSON结构: { "users": [ "User1", "User2", "User3" ] } 我试过这个: with open('data/users.json', 'r') as json_file: json_data = json.load(json_file) user_list = json_data["users"] with open('dat

我试图在json文件中添加一个带有新名称的列表

JSON结构:

{
    "users": [
        "User1",
        "User2",
        "User3"
    ]
}
我试过这个:

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)
但结果是这样的:

["User1", "User2", "User3", "User4"]

为什么以及如何修复它?

您需要编写整个数据字典,而不仅仅是列表

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)

您需要编写整个数据字典,而不仅仅是列表

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)

您转储了错误的内容:
json.dump(json\u数据,json\u文件)
没有什么要解释的,您只是转储了错误的内容,因为您将数据添加为
列表,而json数据更像是
字典
?@Adriano json中的列表可以和字典一样多,它们只是让访问数据变得更加麻烦。但这本身并不会降低它们的有效性。您转储了错误的内容:
json.dump(json\u数据,json\u文件)
无需解释,您只是转储了错误的内容,因为您将数据添加为
列表
,虽然JSON数据更像是一个
字典
?@Adriano,但JSON中的列表可能与字典一样多,这只会让访问数据变得更麻烦。但这本身并没有降低它们的有效性。