我想将 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)
问题:
我想遍历这些项目并将其附加到各种列表,但我只能通过它们的键访问它们,例如 tree['Root']
会给出 Child1, 2, 3 然后是 tree[ 'Root']['child3']
应该给我另外两个成员。但是,此方法在我的用例中不可扩展,我在 JSON 文件中有 1400 个分支(嵌套很深),我想为它们创建 1400 个列表。
有什么想法可以有效地做到这一点吗?
最佳答案
使用 yield from
来自 Python 3.3+ 的语句和一个递归函数:
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']]
关于python - 如何将 JSON 树的每个分支转换为项目列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46546035/