-3

I want to recurse the following nested json string in python.

{
  "hierarchy": {
    "record": {
      "id": 1,
      "record": [
        {
          "id": 2,
          "record": [
            {
              "id": 3,
              "record": [
                {
                  "id": 4,
                  "record": []
                },
                {
                  "id": 5,
                  "record": []
                }
              ]
            }
          ]
        },
        {
          "id": 6,
          "record": [
            {
              "id": 7
            }
          ]
        }
      ]
    }
  },
  "type": "record"
}

and get flattened result as follows.

record_field    id  parent_id
=============================
record          1   null
record          2   1
record          3   2

record          4   3
record          5   3

record          6   1
record          7   6

I am using recursive function but not yet successful to get that expected result. Any help of solution would be great.

Ivan Vinogradov
  • 4,269
  • 6
  • 29
  • 39
user400058
  • 111
  • 1
  • 1
  • 7
  • 3
    Please, also include your attempts. Check [\[SO\]: How to create a Minimal, Complete, and Verifiable example (mcve)](https://stackoverflow.com/help/mcve). – CristiFati May 17 '18 at 15:22

1 Answers1

1

Thanks for the links it did help. I was missing from in "yield from"

def iter_cls(parentId, obj):
    if (len(obj)>0):
        for obj_item in obj:
            yield (parentId, obj_item.get("id"), obj_item.get("classifKey"))
            yield from iter_cls(obj_item.get("id"), obj_item.get("record"))

data = json.loads(str)
cls_data = data["hierarchy"]
top_cls = cls_data["record"]
top_cls_id = top_cls["id"]

l = ("{0}|{1}|{2}".format(ParendID,id,name)
        for (pid, id, name, clevel) in iter_cls(top_cls_id,top_cls["record"])
     )
user400058
  • 111
  • 1
  • 1
  • 7