JSONPath 是一种用于从 JSON 文档中提取数据的查询语言,类似于 XML 的 XPath。它提供了一种简单的方式来导航和提取 JSON 结构中的数据。
| 表达式 | 描述 | 示例 |
|---|---|---|
$ |
根对象或元素 | $.store.book[0].title |
@ |
当前对象或元素(在过滤表达式中使用) | $.store.book[?(@.price < 10)] |
. 或 [] |
子元素操作符 | $.store.book[0].title 或 $['store']['book'][0]['title'] |
* |
通配符,匹配所有元素 | $.store.book[*].author |
.. |
递归下降,搜索所有层次 | $..author |
[start:end:step] |
数组切片操作 | $.store.book[0:3] |
?(expression) |
过滤表达式 | $.store.book[?(@.price < 10)] |
以下示例将使用这个 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
}
},
"expensive": 10
}
JSONPath: $.store.book[*].author
结果: ["Nigel Rees", "Evelyn Waugh", "Herman Melville", "J.R.R. Tolkien"]
JSONPath: $..author
结果: ["Nigel Rees", "Evelyn Waugh", "Herman Melville", "J.R.R. Tolkien"]
JSONPath: $.store.*
结果: [book数组, bicycle对象]
JSONPath: $.store.book[*].price
结果: [8.95, 12.99, 8.99, 22.99]
JSONPath: $.store.book[2]
结果: {"category": "fiction", "author": "Herman Melville", "title": "Moby Dick", "isbn": "0-553-21311-3", "price": 8.99}
JSONPath: $.store.book[-1]
结果: {"category": "fiction", "author": "J.R.R. Tolkien", "title": "The Lord of the Rings", "isbn": "0-395-19395-8", "price": 22.99}
JSONPath: $.store.book[0:2]
结果: [第一本书, 第二本书]
JSONPath: $.store.book[?(@.price < 10)]
结果: [第一本书, 第三本书]
JSONPath: $.store.book[?(@.isbn)]
结果: [第三本书, 第四本书]
JSONPath: $.store.book[?(@.price > $.expensive)]
结果: [第二本书, 第四本书]
JSONPath 有多种编程语言的实现:
注意:不同实现之间可能有细微的语法差异,请参考具体实现的文档。