【问题标题】:append new data to json file in python将新数据附加到python中的json文件
【发布时间】:2018-05-14 15:30:36
【问题描述】:

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

[{"type": "Even", "id": 1}, {"type": "Odd", "id": 2}, {"type": "Even", "id": 3}]

我正在尝试使用此代码将新数据附加到此 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)

但我得到了这个结果

[{"id": 1, "type": "Even"}, {"id": 2, "type": "Odd"}, {"id": 3, "type": "Even"}, [{"id": 4, "type": "Even new"}, {"id": 5, "type": "Odd new"}`]]

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

    [{"id": 1, "type": "Even"}, {"id": 2, "type": "Odd"}, {"id": 3, "type": "Even"}, {"id": 4, "type": "Even new"}, {"id": 5, "type": "Odd new"}`]

我做错了什么?

【问题讨论】:

  • 我认为你只需要将data.append(dict_data) 替换为data.extend(dict_data)

标签: python json python-3.x dictionary


【解决方案1】:

看起来您的变量dict_data 不包含单个dict,而是listdicts。你 .appending 那个 list 在外部 list 里面,从而生成一个嵌套结构

如果是这种情况,那么只需使用.extend 将原来的list 扩展为另一个list

data.extend(dict_data)

考虑将变量dict_data 的名称更改为更有意义的名称,因为它甚至不包含dict,因此阅读您的代码会造成混淆。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-16
    • 2016-04-27
    • 1970-01-01
    • 1970-01-01
    • 2021-06-23
    相关资源
    最近更新 更多