功能 | JSONPath符号 | XPath符号 | 描述 |
---|---|---|---|
根节点 | $ | / | 访问JSON或XML的根节点 |
子节点 | . | / | 访问当前节点的子节点 |
所有子节点 | * | * | 访问当前节点的所有子节点 |
数组索引 | [n] | [n] | 访问数组的第n个元素 |
所有数组元素 | [*] | * | 访问数组中的所有元素 |
合并操作符 | [,] | 访问若干个元素 | |
切片运算符 | [:] | 访问若干个元素,左闭右开 | |
递归下级 | .. | // | 访问当前节点及其所有子孙节点 |
过滤条件 | [?()] | [condition] | 根据条件筛选节点 |
返回的结果均为数组
json{
"store": {
"book": [
{
"category": "reference",
"price": 8.95
},
{
"category": "fiction",
"price": 18.95
}
],
"bicycle": {
"color": "red",
"price": 9.95
},
"candy": [
2, 10, 7, 9, 8, 5, -1
]
}
}
$
json[
{
"store": {
"book": [
{
"category": "reference",
"price": 8.95
},
{
"category": "fiction",
"price": 18.95
}
],
"bicycle": {
"color": "red",
"price": 9.95
},
"candy": [
2, 10, 7, 9, 8, 5, -1
]
}
}
]
$.store
json[
{
"book": [
{
"category": "reference",
"price": 8.95
},
{
"category": "fiction",
"price": 18.95
}
],
"bicycle": {
"color": "red",
"price": 9.95
},
"candy": [
2, 10, 7, 9, 8, 5, -1
]
}
]
$.store.*
| $.store[*]
json[
[
{
"category": "reference",
"price": 8.95
},
{
"category": "fiction",
"price": 18.95
}
],
{
"color": "red",
"price": 9.95
},
[
2, 10, 7, 9, 8, 5, -1
]
]
$.store.book[1]
json[
{
"category": "fiction",
"price": 18.95
}
]
$.store.book[*]
json[
{
"category": "reference",
"price": 8.95
},
{
"category": "fiction",
"price": 18.95
}
]
$.store..category
json[
"reference",
"fiction"
]
$.store[?(@.price < 10)]
json[
{
"color": "red",
"price": 9.95
}
]
$.store.[?(@.price < 10)]
json[
{
"color": "red",
"price": 9.95
},
{
"category": "reference",
"price": 8.95
}
]
$..candy.[1,3,2]
| $..candy[1,3,2]
json[
10,
9,
7
]
$..candy.[1:3]
| $..candy[1:3]
json[
10,
7
]
https://github.com/h2non/jsonpath-ng
https://pypi.org/project/jsonpath-ng/
pip install jsonpath-ng
pip install jsonpath-ng[ext]
(扩展包)
pythonimport json
from jsonpath_ng.ext import parse
json_string = '{"store": ["xxx"]}'
data = json.loads(json_string)
expression = parse('$.store')
authors = [match.value for match in expression.find(data)]
print(authors) # [['xxx']]