我在 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/