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

标签 python json python-3.x dictionary

我在 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"}`]

我做错了什么?

最佳答案

看起来你的变量dict_data不包含单个dict,而是包含dict列表 。您在外部列表.append列表,从而生成嵌套结构

如果是这种情况,则只需使用 .extend 将原始 list 扩展为另一个 list:

data.extend(dict_data)

考虑将变量 dict_data 的名称更改为更有意义的名称,因为它甚至不包含 dict,因此读取代码会很困惑。

关于python - 将新数据附加到python中的json文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47577927/

相关文章:

python - 使用以每小时时间序列作为输入的 LSTM 预测每日值(value)

python - 如何使用环境变量建立 psycopg2 连接?

json - facebook graph api 的 Swagger 文档

c# - 在 C# 中反序列化可能是整数或字符串列表的 JSON

c# - WCF 应答处理 C#

python-3.x - 调用 z :com. amazonaws.services.glue.util.Job.commit 时出错。未初始化

python - 如何以像素为单位调整按钮大小? (Tkinter)

python - 如何对 groupby 对象中没有时间列的基于时间的列进行排序

python - 没有 sudo 的语法错误

python - 如何使用 Python 解析某些 .csv 行? (包含示例文件)