zoukankan      html  css  js  c++  java
  • Python_jsonPath模块的使用

    jsonpath简介

    如果有一个多层嵌套的复杂字典,想要根据key批量提取value,还是比较繁琐的。jsonPath模块就能解决这个痛点,接下来我们来学习一下jsonpath模块。

    因为jsonpath是第三方模块,想要使用需要安装

    pip install jsonpath

    jsonpath使用方法

    import jsonpath
    res=jsonpath.jsonpath(dict_data,'jsonpath语法规则字符串')

    根据给定jsonpath语法规则,在dict_data中若能找到对应的数据,则以list类型返回数据,若找不到则返回false。

    jsonpath语法规则

    jsonpath使用示例

    book_dict = {
            "book": [
                    {"category": "reference",
                     "author": "Nigel Rees",
                     "title": "Sayings of the Century",
                     "price": 8.95
                     },
                    {"category": "fiction",
                     "author": "Evelyn Waugh",
                     "title": "Sword of Honour",
                     "price": 12.99
                     },
                    {"category": "fiction",
                     "author": "Herman Melville",
                     "title": "Moby Dick",
                     "isbn": "0-553-21311-3",
                     "price": 8.99
                     },
                    {"category": "fiction",
                     "author": "J. R. R. Tolkien",
                     "title": "The Lord of the Rings",
                     "isbn": "0-395-19395-8",
                     "price": 22.99
                     }
            ],
            "bicycle": {
                    "color": "red",
                    "price": 19.95
            }
    }
    
    from jsonpath import jsonpath
    
    # 获取price的所有值
    print(jsonpath(book_dict, '$..price'))
    
    # 获取book下面所有元素
    print(jsonpath(book_dict, "$.book.*"))
    
    # 获取book下面所有price的值
    print(jsonpath(book_dict, "$.book[*].price"))
    print(jsonpath(book_dict, "$.book..price"))
    
    # 获取第1本书所有信息
    print(jsonpath(book_dict, "$.book[0]"))
    
    # 获取第2~3本书所有信息
    print(jsonpath(book_dict, "$.book[1:3]"))
    
    # 获取最后一本书
    print(jsonpath(book_dict, "$.book[(@.length-1)]"))
    
    # 获取包含了isbn的所有书
    print(jsonpath(book_dict, "$.book[?(@.isbn)]"))
    
    # 获取书的价格小于10的书
    print(jsonpath(book_dict, "$.book[?(@.price<10)]"))

    执行结果

  • 相关阅读:
    oracle循环语句
    解决使用Properties读取中文乱码问题
    oracle常用& to_date()怎么转换带am pm的时间格式
    distinct 多列详解
    javascript中遍历EL表达式List集合中的值
    最近一段时间代码汇总
    JAVA基础之对象的初始化
    求解圆圈中最后剩下的数字
    删除有序链表中的重复结点
    构造二叉树,并求解树的高度
  • 原文地址:https://www.cnblogs.com/testlearn/p/14818212.html
Copyright © 2011-2022 走看看