基本语法
JSONPath语法元素和对应XPath元素的对比
| XPath | JSONPath | Description | 
| / | $ | 根元素 | 
| . | @ | 当前元素 | 
| / | . or [] | 子元素 | 
| .. | n/a | 父元素 | 
| // | .. | 递归下降,JSONPath是从E4X借鉴的。 | 
| * | * | 通配符,表示所有的元素 | 
| @ | n/a | 属性访问字符 | 
| [] | [] | 子元素操作符 | 
| [,] | 连接操作符在XPath 结果合并其它结点集合。JSONP允许name或者数组索引。 | |
| n/a | [start: end: step] | 数组分割操作从ES4借鉴。 | 
| [] | ?() | 应用过滤表示式 | 
| n/a | () | 脚本表达式,使用在脚本引擎下面。 | 
| () | n/a | Xpath分组 | 
示例对比
| XPath | JSONPath | 结果 | 
| /store/book/author | $.store.book[*].author | 书点所有书的作者 | 
| //author | $..author | 所有的作者 | 
| /store/* | $.store.* | store的所有元素。所有的bookst和bicycle | 
| /store//price | $.store..price | store里面所有东西的price | 
| //book[3] | $..book[2] | 第三个书 | 
| //book[last()] | $..book[(@.length-1)] | 最后一本书 | 
| //book[position() < 3] | $..book[0,1] $..book[:2] | 前面的两本书 | 
| //book[isbn] | $..book[?(@.isbn)] | 过滤出所有的包含isbn的书。 | 
| //book[price<10] | $..book[?(@.price<10)] | 过滤出价格低于10的书。 | 
| //* | $..* | 所有元素。 | 
xpath索引下标是从1开始的
jsonpath索引下标是从0开始
Python中使用
安装依赖
pip install jsonpath代码示例
# -*- coding: utf-8 -*-
import jsonpath
data = {
    "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
             }
        ],
        "bicycle": {
            "color": "red",
            "price": 19.95
        }
    }
}
ret = jsonpath.jsonpath(data, '$.store.book[*].author')
print(ret)
# ['Nigel Rees', 'Evelyn Waugh']
ret = jsonpath.jsonpath(data, '$..author')
print(ret)
# ['Nigel Rees', 'Evelyn Waugh']
ret = jsonpath.jsonpath(data, '$.store..price')
print(ret)
# [8.95, 12.99, 19.95]
ret = jsonpath.jsonpath(data, '$..book[1].title')
print(ret)
# ['Sword of Honour']
ret = jsonpath.jsonpath(data, '$..book[?(@.price<10)].title')
print(ret)
# ['Sayings of the Century']参考
- https://goessner.net/articles/JsonPath/
- JSONPath-简单入门










