简体   繁体   中英

How do I use python to iterate JSON output with repeating sets of the same keys?

I'm trying to use python to create hundreds of repeating sets of JSON output that looks like this:

    {
      "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 ...

But when I use code like this, each new set overwrites the last, so I only end up with one set in the end.

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)

How do I build out the JSON output without overwriting anything?

Actually you're creating a dict, not a set, when you do epicdict = {} , so what you're really doing in that code is updating the same dict with keys/values (overriding them). What you want is to use set() and .add() . It would look like this:

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})

Figured it out using "append". I am able to keep appending to the set underneath "root".

epicset = {"root": []}
epicset["root"].append({"children": ["456def"], "dependencies": [], "id": "123abc", "name": "root", "legend": "", "optimistic": 0, "pessimistic": 0, "expected": 0, "min": 0, "max": 0, "distribution": 0, "estimate": 0, "discrete": True, "isProject": True, "state": 1})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM