【发布时间】: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