• JsonPath详解


    JsonPath

    简介
    JsonPath是一种信息抽取类库,是从JSON文档中抽取指定信息的工具

    文档
    http://goessner.net/articles/JsonPath


    安装

    pip install jsonpath



    使用
    注意:这里的json_data为python数据,如列表,字典

    data = jsonpath.jsonpath(json_data, 匹配规则)

    语法

    路径操作符
    $  根对象
    .  选择当前层级的属性或数组元素
    .. 选择所有符合条件的条件
    *  通配符,匹配任意属性或数组元素

    其余
    @    现行节点
    n/a    取父节点,Jsonpath未支持
    n/a    根据属性访问,Json不支持,因为Json是个Key-value递归结构,不需要。
    [,]    支持迭代器中做多选。
    ?()    支持过滤操作.
    ()    支持表达式计算
    n/a    分组,JsonPath不支持

    基础示例

    1. import jsonpath
    2. json_dict_data = {
    3.     "name": "John",
    4.     "age": 30,
    5.     "cities": ["New York", "London"],
    6.     "scores": {
    7.         "math": 90,
    8.         "english": 85,
    9.         "science": 95
    10.     },
    11.     "isNullValue": None
    12. }
    13. # 提取根对象下的 name 属性值
    14. result_name = jsonpath.jsonpath(json_dict_data, "$.name")
    15. print(result_name)
    16. # 提取根对象下 cities 数组的第一个元素
    17. result = jsonpath.jsonpath(json_dict_data, "$.cities[0]")
    18. print(result)
    19. # 提取根对象下 scores 对象的math属性值
    20. result = jsonpath.jsonpath(json_dict_data, "$.scores.math")
    21. print(result)

    爬虫示例【urllib版】

    1. import json
    2. import jsonpath
    3. from urllib.request import Request, urlopen
    4. from fake_useragent import UserAgent
    5. def cra1_1():
    6.     url = 'http://xxx:8031/front/website/findAllTypes'
    7.     headers = {'User-Agent': UserAgent().chrome}
    8.     requests = Request(url, headers=headers)
    9.     resp = urlopen(requests)
    10.     result = json.loads(resp.read().decode())
    11.     data1 = jsonpath.jsonpath(result, '$.code')
    12.     print(data1)
    13. if __name__ == '__main__':
    14.     cra1_1()

    爬虫示例【requests版】

    1. import jsonpath
    2. from fake_useragent import UserAgent
    3. import requests
    4. def cra1_1():
    5.     url = 'http://xxx:8031/front/website/findAllTypes'
    6.     headers = {'User-Agent': UserAgent().chrome}
    7.     resp = requests.get(url, headers=headers)
    8.     result = resp.json()
    9.     code = jsonpath.jsonpath(result, '$.code')
    10.     print(code)
    11. if __name__ == '__main__':
    12.     cra1_1()

  • 相关阅读:
    Kafka原理剖析之「位点提交」
    【LeetCode】210. 课程表 II——拓扑排序
    Nacos服务发现数据模型
    分享一个程序员接私活、兼职的平台
    C++学习笔记--函数重载(2)
    开源博客项目Blog .NET Core源码学习(5:mapster使用浅析)
    输入学生成绩(最多不超过40),输入为负值时表示输入结束,统计成绩高于平均成绩的学生人数
    IOS 发布遇到“Unable to authenticate with App Store Connect”错误咋解决?
    2024年8月7日(mysql主从 )
    win部署CRM
  • 原文地址:https://blog.csdn.net/m0_63040701/article/details/133187704