首页 > 解决方案 > objectpath json查询以在python中获取数组值

问题描述

我有一些 JSON,如下所示:

{
"books": [
    {
        "name": "Matthew"
    },
    {
        "name": "Mark",
        "sections": [
            {
                "reference": "1:1-1:8",
                "tags": [
                    "a",
                    "b"
                ],
                "summary": "blah",
                "notes": ""
            },
            {
                "reference": "1:9-1:15",
                "tags": [
                    "b",
                    "c",
                    "d"
                ],
                "summary": "",
                "notes": ""
            }
        ]
    }
]

}

我想使用 objectpath 获取所有部分的列表。

我试过了:

sections = Tree(db).execute('$.books[@.name is "Mark"].sections')
for section in sections:
    print(section)
    print("----\n")

但返回的是一个单独的部分,它是一个数组。也就是说,节只有一个结果,而我只期望(或至少想要)“节”数组。这将节省我在 for 循环中的 for 循环。

是否有一些特殊的语法让它返回我想要的方式?

我也试过:

'$.books[@.name is "Mark"].sections.*'
'$.books[@.name is "Mark"].sections[*]'

没有运气。

标签: pythonjsonobjectpath

解决方案


section是一个生成器对象。要从中获取第一项,您可以使用next()函数:

sections = Tree(db).execute('$.books[@.name is "Mark"].sections')
print(sections) # will show that it's a generator
for section in next(sections):
    print(section)
    print("----\n")

第一项将是包含各个部分的列表。现在您可以使用 for 循环遍历每个部分。


推荐阅读