# !/usr/local/bin/python3
# coding=utf-8
from jsonpath import jsonpath
from pprint import pprint
jsons = {
"code": 0,
"data": {
"list": [
{
"id": "37433",
"related_id": "",
"name": "研发中心",
"level": "2",
"has_child": True,
"employee_num": 20,
"disabled": False,
"sub_role_checked": True
},
{
"id": "38460",
"related_id": "",
"name": "智校",
"level": "2",
"has_child": True,
"employee_num": 1,
"disabled": False,
"sub_role_checked": True,
"age": 28
}
]
},
"error": {
},
"extra": {
"cost": 0.07595086097717285,
"request-id": "6e0c03a56b5f4c188e6843222a4c71fb@3@service"
}
}
# 获取list中所有的name值,以下两种方法结果一样
names = jsonpath(jsons, '$.data.list[*].name')
names1 = jsonpath(jsons, '$..name')
names2 = jsonpath(jsons, '$.data..name')
# 获取list中第1个name值,以下两种方法结果一样
name = jsonpath(jsons, '$.data.list[0].name')
name1 = jsonpath(jsons, '$..name')[0]
# 获取list中第2条数据
list2 = jsonpath(jsons, '$..list[1]')
# 获取list中第2条数据的属性列表
list3 = jsonpath(jsons, '$..list[1][*]')
# 获取list中第2条数据的id和name
list4 = jsonpath(jsons, '$..list[1][id,name]')
# 获取list中前1条数据
list5 = jsonpath(jsons, '$..list[:1]')
# 获取包含age属性的list数据
ages = jsonpath(jsons, '$..list[?(@.age)]')
# 获取employee_num小于10的list数据
list6 = jsonpath(jsons, '$..list[?(@.employee_num<10)]')
pprint(list6)
jsonpath 语法参照
于 2023-02-24 17:13:34 首次发布