Python -JSONPATH

python-jsonpath

一、概念

jsonpath 解析多层嵌套json数据。信息抽取类库,从JSON文档中抽取指定信息的工具。

二、安装

pip3 install jsonpath

三、导入

from jsonpath import jsonpath
import jsonpath

四、基本使用

JsonPath描述描述
$根节点
@现行节点
. or []取子节点
不管位置,选择所有符合条件的节点
*匹配所有元素节点
[]迭代器(可以在里边做简单的迭代操作,如数组下标,根据内容选值等)
[,]支持迭代器中做多选
?()支持过滤操作
()支持表达式计算

五、具体使用场景

from jsonpath import jsonpath

canshu = {
    "data": {
        "customConfigs": [
            {
                "key": "pushType",
                "value": "YC"
            },
            {
                "key": "commitType",
                "value": "YC"
            },
            {
                "key": "outerSource",
                "value": "333"
            },
            {
                "key": "channelSource",
                "value": "444"
            },
            {
                "key": "mediaSource",
                "value": "555"
            },
            {
                "key": "name",
                "value": "1"
            },
            {
                "key": "city",
                "value": "1"
            },
            {
                "key": "forceQuickFlag",
                "value": "1"
            },
            {
                "key": "carFinance",
                "value": "1"
            },
            {
                "key": "source",
                "value": "xezdzdxKD"
            }
        ],
        "flowTarget": "1"
    },
    "grayPackages": "",
    "jumpUrl": "",
    "responseCode": "000000",
    "responseMsg": "成功"
}
pt = jsonpath(canshu, '$.responseCode123')
print(pt, type(pt))  #当查找不存在的key就会返回 False <class 'bool'>

pt1 = jsonpath(canshu, '$.responseCode')
print(pt1, type(pt1))  # ['000000'] <class 'list'>
print(pt1[0], type(pt1[0]))  # 000000 <class 'str'>

pt2 = jsonpath(canshu, '$.data.customConfigs')
print(pt2, type(pt2))  # [[{'key': 'pushType', 'value': 'YC'}....后面不写了

pt3 = jsonpath(canshu, '$.data.customConfigs[0]')
print(pt3, type(pt3))  # [{'key': 'pushType', 'value': 'YC'}] <class 'list'>
pt4 = jsonpath(canshu, '$.data.customConfigs[0].key')
print(pt4, type(pt4))  # ['pushType'] <class 'list'>

pt5 = jsonpath(canshu, '$..key')[-1:]
print(pt5, type(pt5))  # ['source'] <class 'list'>
#使用’@'符号表示当前的对象,?(<判断表达式>) 使用逻辑表达式来过滤。
pt6 = jsonpath(canshu, '$.[?(@.key== "pushType")].value')
print(pt6, type(pt6))  # ['YC'] <class 'list'>

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值