python - 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[*]'
没有运气。
解决方案
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 循环遍历每个部分。
推荐阅读
- flutter - 在不同的屏幕尺寸上运行时的不同结果
- android - This release is not compliant with the Google Play 64-bit requirement Google Warning
- c++ - 为什么 GCC 在复制赋值操作中拒绝 const 引用?
- android - 使用最新的 com.jakewharton.rxbinding3:rxbinding:3.0.0-alpha2 库时未找到 RxTextView 和其他小部件
- reactjs - 如何使用文件对象设置状态(反应)
- c# - Visual Studio 2017 C#,调试异步代码,看不到局部变量
- javascript - 如何创建使用 ajax 更新的自定义购物车数量?
- javascript - 创建一个花哨的循环表
- kubernetes - Rancher 显示警报但未收到电子邮件?
- excel - 具有相同类型名称的 Web 抓取按钮和字段