Python 使用 jsonpath 解析 json

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")

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容