举例说明jsonpath方法的使用
时间: 2023-10-12 15:06:01 浏览: 84
假设我们有如下的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",
"author": "Herman Melville",
"title": "Moby Dick",
"isbn": "0-553-21311-3",
"price": 8.99
},
{
"category": "fiction",
"author": "J. R. R. Tolkien",
"title": "The Lord of the Rings",
"isbn": "0-395-19395-8",
"price": 22.99
}
],
"bicycle": {
"color": "red",
"price": 19.95
}
}
}
```
现在我们想要获取所有图书的价格,我们可以使用jsonpath方法来实现:
```python
import json
from jsonpath_ng import jsonpath, parse
# 解析JSON数据
data = json.loads('''
{
"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",
"author": "Herman Melville",
"title": "Moby Dick",
"isbn": "0-553-21311-3",
"price": 8.99
},
{
"category": "fiction",
"author": "J. R. R. Tolkien",
"title": "The Lord of the Rings",
"isbn": "0-395-19395-8",
"price": 22.99
}
],
"bicycle": {
"color": "red",
"price": 19.95
}
}
}
''')
# 解析jsonpath表达式
expression = parse('$.store.book[*].price')
# 使用jsonpath表达式获取数据
for match in expression.find(data):
print(match.value)
```
运行上述代码,会输出所有图书的价格:
```
8.95
12.99
8.99
22.99
```
阅读全文