jsonpath 通過通用的表達式可以獲取json中指定的值。
Python中jsonpath的使用
1、使用jsonpath需要安裝jsonpath,在pycharm中執(zhí)行命令:
pip install jsonpath
2、具體使用
$ 根節(jié)點(root)
. 子節(jié)點(一個點)
.. 子孫節(jié)點(兩個點) 遞歸搜索
(*) 通配符,表示所有的元素
[] 子節(jié)點
?() 條件過濾
@ 代表當前元素
3、實例說明
import jsonpath
student_info = {
"code":null,
"success":true,
"data":{
"message":null,
"students":[
{
"name":"小明",
"detail":{
"sex":"男",
"age":28,
"height":174
}
},
{
"name":"小紅",
"detail":{
"sex":"女",
"age":20,
"height":162
}
}
]
}
}
# 獲取所有學(xué)生
res = jsonpath.jsonpath(student_info ,"$..students")
# 獲取所有的name
res = jsonpath.jsonpath(student_info,"$..students.[*].name")
返回:
['小明', '小紅']
# 獲取年齡大于20的學(xué)生的性別
res = jsonpath.jsonpath(student_info, "$.data.students.[*].detail[?(@.age > 20)].sex")
也可以這樣寫:
res = jsonpath.jsonpath(student_info, "$..[*]..[?(@.age > 20)].sex")
print(res)
# 獲取第2個學(xué)生的信息
res = jsonpath.jsonpath(student_info, '$.data.students[1]')
# 獲取姓名為小明的學(xué)生的年齡
res = jsonpath.jsonpath(student_info, "$.data.students.[?(@.name=='小明')]..age")