安装
pip install jsonpath
# 或者
pip install jsonpath -i https://pypi.tuna.tsinghua.edu.cn/simple
使用
from jsonpath import jsonpath
ret = jsonpath(json_dict, 'jsonpath语法规则字符串')
jsonpath语法规则
JSONPath | 描述 |
---|---|
|
表示根元素 |
|
当前元素 |
or
|
子元素 |
|
父元素,jsonpath未支持 |
|
不管位置,选择符合条件的元素 |
|
匹配所有元素节点 |
|
根据属性访问,jsonpath未支持,因为json是一个key:value的递归结果,不需要属性访问。 |
|
迭代器标示,可以在里面做简单的迭代操作,如数组下标、根据内容选值等。 |
|
支持迭代器做多选 |
|
支持过滤操作 |
|
支持表达式计算 |
|
分组,jsonpath未支持 |
举例
from jsonpath import jsonpath
book_dict = {
"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
}
}
}
res = jsonpath(book_dict, '$.store.book[*].author ')
print(res)
#索引从0开始 [索引]
res = jsonpath(book_dict , '$.store.book[0]')
print(res)
#根据条件筛选 ?(@.字段>数值)
# .. 直达选中字段
res = jsonpath(book_dict, '$..book[?(@.price>10)]')
print(res)
JSONPath | 描述 |
---|---|
|
获取store中所有的book的作者 |
|
获取所有的作者 |
|
获取store下的所有的元素 |
|
获取store中的所有的图书的价格 |
|
获取第三本书 |
|
获取最后一本书 |
|
获取前两本书 |
|
获取有isbn的所有书 |
|
获取价格大于10的所有图书 |
|
获取所有的数据 |
版权声明:本文为ALL_BYA原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。