小编Ras*_*san的帖子

将新数据追加到python中的json文件

我在data.json文件中有下面的json数组

[{"type": "Even", "id": 1}, {"type": "Odd", "id": 2}, {"type": "Even", "id": 3}]
Run Code Online (Sandbox Code Playgroud)

我试图使用此代码将新数据追加到此json文件

    def foo(filename, dict_data):
    with open(filename, 'r') as json_data: 
        data = json.load(json_data)

    data.append(dict_data)

    with open(filename, 'w') as json_data: 
        json.dump(data, json_data)

    foo('data.json', lst)
Run Code Online (Sandbox Code Playgroud)

但我得到这个结果

[{"id": 1, "type": "Even"}, {"id": 2, "type": "Odd"}, {"id": 3, "type": "Even"}, [{"id": 4, "type": "Even new"}, {"id": 5, "type": "Odd new"}`]]
Run Code Online (Sandbox Code Playgroud)

但这是无效的json数据。 我的预期数据是

    [{"id": 1, "type": "Even"}, {"id": 2, "type": "Odd"}, {"id": 3, "type": "Even"}, {"id": 4, "type": "Even new"}, {"id": 5, "type": …
Run Code Online (Sandbox Code Playgroud)

python json dictionary python-3.x

5
推荐指数
1
解决办法
1407
查看次数

标签 统计

dictionary ×1

json ×1

python ×1

python-3.x ×1