How to convert each branch of a JSON tree into a list of items?
我想将JSON树结构的每个分支转换为该分支中的项目列表。我想用循环来实现,但是我不能用索引来访问对象。
1 2 3 4 5 6 7 8 9 | Example JSON: { "Root": {"child1":"abc", "child2":"def", "child3": {"grandchild1":"nick", "grandchild2":"Sam" } } } |
我要遍历它们并按以下方式存储它们:
1 2 3 4 | list1 = ['Root',"child1","abc"] list2 = ['Root',"child2","def"] list3 = ['Root',"child3","grandchild1","nick",] list4 = ['Root',"child3","grandchild2","sam",] |
我阅读JSON如下:
1 2 3 4 | import json with open('sample.json') as f: tree = json.load(f) |
问题:我想循环浏览这些项目并将其附加到各种列表中,但我只能通过它们的键访问它们,如
有什么办法能有效地做到这一点吗?
使用Python语言
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | 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)) |
将输出:P></
1 2 3 4 | [['Root', 'Child1', 'abc'], ['Root', 'Child2', 'def'], ['Root', 'Child3', 'grandchild1', 'nick'], ['Root', 'Child3', 'grandchild2', 'Sam']] |