如何将JSON树的每个分支转换为项目列表?

我想将
JSON树结构的每个分支转换为该分支中的项列表.我想用循环来做,但我无法使用索引访问对象.

Example JSON:
{
    "Root": { "child1": "abc",
              "child2": "def",
              "child3": { "grandchild1": "nick",
                           "grandchild2": "Sam"
                        }
             }
 }

我想遍历它们并将它们存储如下:

list1 = ['Root', "child1", "abc"]
list2 = ['Root', "child2", "def"]
list3 = ['Root', "child3", "grandchild1", "nick",]
list4 = ['Root', "child3", "grandchild2", "sam",]

我读了JSON如下:

import json

with open('sample.json') as f:
    tree = json.load(f)

问题:
我想循环遍历这些项目并将其附加到各种列表但我只能通过他们的键访问它们,如树[‘Root’]会给Child1,2,3然后树[‘Root’] [‘child3’]应该给我另外两个成员.但是,在我的用例中,此方法不可伸缩,我在JSON文件中有1400个分支(非常深嵌套),我想为它们创建1400个列表.

任何想法如何有效地做到这一点?

最佳答案 使用Python 3.3中的
yield from语句和递归函数:

tree = {
"Root": { "Child1": "abc",
          "Child2": "def",
          "Child3": { "grandchild1": "nick",
                      "grandchild2": "Sam"
                    }
         }
}

def walk_json(tree, path=[]):
    try:
        for root, child in tree.items():
            yield from walk_json(child, path + [root])
    except AttributeError: # in case .items() is not possible (on leaves)
        yield path + [tree]

list(walk_json(tree))

将输出:

[['Root', 'Child1', 'abc'],
['Root', 'Child2', 'def'],
['Root', 'Child3', 'grandchild1', 'nick'],
['Root', 'Child3', 'grandchild2', 'Sam']]
点赞