递归嵌套的json对象

时间:2018-05-17 15:16:10

标签: python python-3.x

我想在python中递归下面嵌套的json字符串。

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

并得到扁平的结果如下。

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

我正在使用递归函数但尚未成功获得预期结果。任何解决方案的帮助都会很棒。

1 个答案:

答案 0 :(得分:0)

感谢您提供帮助的链接。我从"

中收获了
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"])
     )
相关问题