Python自带的json库可以把请求转为字典格式, 但在多层嵌套的字典中取值往往要进行多次循环遍历才能取到相应的数据, 如:
res_dict = { "code": 0, "msg": "成功", "data": { "users": [ {"name": "张三", "gender": "male", "age": 12}, {"name": "李四", "gender": "female", "age": 15}, {"name": "王五", "gender": "male", "age": 22}, {"name": "赵六", "gender": "male", "age": 24}, ], "goods": [ {"name": "apple", "price": 15, "num": 200}, {"name": "pear", "price": 18, "num": 100}, {"name": "banana", "price": 16, "num": 210}, ] } }
- 获取所有用户名?
- 如果users是动态的(有可能是users123,或users567)怎么获取下面的数据?
- 怎么快说获取年龄大于20的用户?
这种类型的操作用字典遍历往往就麻烦的多, 特别是遇到动态节点更是无从下手
jsonpath则可以很好的解决这个问题。
主要特点
- 支持路径及*模糊匹配
- 支持索引和类似切片功能
- 支持表达式筛选
jsonpath安装
pip install jsonpath
jsonpath基本语法
jsonpath使用示例
from jsonpath import jsonpath
res_dict = {
"code": 0,
"msg": "成功",
"data": {
"users": [
{"name": "张三", "gender": "male", "age": 12},
{"name": "李四", "gender": "female", "age": 15},
{"name": "王五", "gender": "male", "age": 22},
{"name": "赵六", "gender": "male", "age": 24},
],
"goods": [
{"name": "apple", "price": 15, "num": 200},
{"name": "pear", "price": 18, "num": 100},
{"name": "banana", "price": 16, "num": 210},
]
}
}
# 匹配结果为一个列表, 无结果返回False
# 1. 逐级取值, 可使用*代表任意节点 .. 表示任意路径
print(jsonpath(res_dict, "$.msg"))
print(jsonpath(res_dict, "$.data.*")) # data下的任意节点(users/goods)下的数据
print(jsonpath(res_dict, "$.data..[2]") # 任意节点(包含users和goods)下的第3个
print(jsonpath(res_dict, "$..users[*].name"))
# 2. 索引和切片
print(jsonpath(res_dict, "$.data.users[2]")) # 第三个数据
print(jsonpath(res_dict, "$.data.users[0:2]")) # 前两条数据
# 表达式
print(jsonpath(res_dict, "$..users[?(@.gender=='female')]")) # 支持和当前数据中的字段比较
更多学习资料请加添加作者微信:lockingfree获取