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

标签 python json python-3.x

我想将 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/

相关文章:

python - Scrapy Splash 截图?

javascript - 打印 JSON 对象数据时控制台上出现未定义消息

python - 我如何有效地将列表的python3列表更改为golang多维数组?

python - Django Rest框架APIView所有方法的代码相同

Python:快速上传大文件S3

javascript - 如何选择 JSON 中存在的几个项目中的第一个?

java - Hibernate 上 @JsonIgnore 的 Jsonparsing 错误

python - 如何在不使用selenium等 headless 浏览器的情况下登录morningstar.com?

Python3 FileNotFoundError 任何文件,使用 subprocess.popen()

python - 在极坐标图中的点周围绘制平滑轮廓