我正在尝试使用python创建数百个重复的JSON输出集,如下所示:
{
"children": [],
"dependencies": [],
"id": "123456",
"name": "Epic 1",
"legend": "",
"optimistic": "13",
"pessimistic": "15",
"expected": "14",
"min": 13,
"max": 15,
"distribution": 0,
"estimate": 0,
"discrete": false,
"isProject": false,
"state": 1
},
{
"children": [],
"dependencies": [],
"id": "234567",
"name": "Epic 2",
"legend": "",
"optimistic": "17",
"pessimistic": "19",
"expected": "18",
"min": 17,
"max": 19,
"distribution": 0,
"estimate": 0,
"discrete": false,
"isProject": false,
"state": 1
}
...
...
... and so on ...
但是当我使用这样的代码时,每个新集都会覆盖最后一个,因此最后我只会得到一个集。
epicdict = {}
for epic in query:
epicdict.update({"id": epic.id, "name": epic.key, "legend": "", "optimistic": opt, "pessimistic": pes, "expected": exp, "min": 0, "max": 0, "distribution": 0, "estimate": 0, "discrete": True, "isProject": True, "state": 1})
print(epicdict)
with open(jsonfile, 'w') as output:
json.dump(epicdict, output)
如何在不覆盖任何内容的情况下构建JSON输出?
答案 0 :(得分:0)
实际上,当您执行epicdict = {}
时,您是在创建字典,而不是集合,因此,您在该代码中真正要做的就是使用键/值(覆盖它们)来更新相同的字典。
您要使用set()
和.add()
。
看起来像这样:
epicdict = set()
for epic in query:
epicdict.add({"id": epic.id, "name": epic.key, "legend": "", "optimistic": opt, "pessimistic": pes, "expected": exp, "min": 0, "max": 0, "distribution": 0, "estimate": 0, "discrete": True, "isProject": True, "state": 1})
答案 1 :(得分:0)
使用“ append”将其弄清楚。我可以继续添加到“根”下面的集合中。
{{1}}