首页 > 解决方案 > 使用 json.dump 创建包含 json 数组的有效 json 文件

问题描述

麦克维:

d1 = {"a":1}
d2 = {"b":2}
import json
with open('test2.json','w+') as file:
     for d in [d1,d2]:
             json.dump(d,file)

test2.json 内容:

{"a": 1}{"b": 2}

期望的结果:

[{"a": 1},{"b": 2}]

我怎样才能实现它?

标签: pythonjson

解决方案


d1 = {"a":1}
d2 = {"b":2}
import json

array = [json.dumps(d) for d in [d1,d2]]

然后将数组写入文件


推荐阅读