JsonPath根据值查找元素(Python)
实战实例
- 需求:从数组json列表中,根据具体数组中的某一个json其中一个字段来取另一个字段值。
- 示例数据如下:
{ "store": {
"book": [
{ "category": "reference",
"author": "Nigel Rees",
"title": "Sayings of the Century",
"price": 8.95
},
{ "category": "fiction",
"author": "Evelyn Waugh",
"title": "Sword of Honour",
"price": 12.99
},
{ "category": "fiction-1",
"author": "Herman Melville",
"title": "Moby Dick",
"isbn": "0-553-21311-3",
"price": 8.99
},
{ "category": "fiction-2",
"author": "J. R. R. Tolkien",
"title": "The Lord of the Rings",
"isbn": "0-395-19395-8",
"price": 22.99
},
.............
.............
.............
]
}
}
- 获取 数据列表中 “category” = “fiction” 这个 book 对象,jsonpath写法如下:
$..*[?(@.category=='reference')]
- 结果如下:
- 要获 对象的另一个属性,就简单了,直接 .price 即可。
在线实验工具:jsonpath在线工具
安装
pip install jsonpath
基本知识
- 官方:https://goessner.net/articles/JsonPath/
- https://juejin.cn/post/6850418109473783816
- https://blog.youkuaiyun.com/myt2000/article/details/120757692
高级知识
根据文本内容查找,获取 节点路径
- JsonPaht 表达式:
"$..*[?(@=='12M7qEpkl85g00')]"
- 示例
jsonpath(json_obj, "$..*[?(@=='12M7qEpkl85g00')]",result_type="IPATH")
返回值:
[['items', '0', 'userId']]
- 路径转换为表达式, 使用引号,可解决中间有空格问题
$.'items'.'0'.'userId'
or
$['items']['0']['userId']