首页 >后端开发 >Python教程 >Python Json读写操作之JsonPath怎么使用

Python Json读写操作之JsonPath怎么使用

PHPz
PHPz转载
2023-04-18 16:43:051145浏览

    Python Json读写操作_JsonPath用法详解

    1. 介绍

    JSONPath是一种信息抽取类库,是从JSON文档中抽取指定信息的工具,提供多种语言实现版本,包括Javascript、Python、PHP和Java。

    JSONPath的安装方法如下:pip install jsonpath

    JSONPath语法和XPATH语法对比,JSON结构清晰,可读性高,复杂度低,非常容易匹配。JSONPath的语法与Xpath类似,如下表所示为JSONPath与XPath语法对比:

    Python Json读写操作之JsonPath怎么使用

    2. 代码示例

    bookJson = {
      "store": {
        "book":[
          { "category": "reference",
            "author": "Nigel Rees",
            "title": "Sayings of the Century",
            "price": 8.95
          },
          { "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
        }
      }
    }

    变量bookJson中已经包含了这段JSON字符串,可通过以下代码反序列化得到JSON对象:

    books=json.loads(bookJson)

    1)查看store下的bicycle的color属性:

    checkurl = "$.store.bicycel.color"
    print(jsonpath.jsonpath(books, checkurl))
    # 输出:['red']

    2)输出book节点中包含的所有对象:

    checkurl = "$.store.book[*]"
    object_list=jsonpath.jsonpath(books, checkurl)
    print(object_list)

    3)输出book节点的第一个对象:

    checkurl = "$.store.book[0]"
    obj = jsonpath.jsonpath(books, checkurl)
    print(obj)
    # 输出: ['category': 'reference', 'author': 'Nigel Rees', 'title': 'Sayings of the Century', 'price': 8.95}]

    4)输出book节点中所有对象对应的属性title值:

    checkurl = "$.store.book[*].title"
    titles = jsonpath.jsonpath(books, checkurl)
    print(titles)
    # 输出: ['Sayings of the Century', 'The Lord of the Rings']

    5)输出book节点中category为fiction的所有对象:

    checkurl = "$.store.book[?(@.category=='fiction')]”
    books=jsonpath.jsonpath(books, checkurl)
    print(books)
    # 输出:[{'category': 'fiction', 'author': 'J. R. R. Tolkien', 'title': 'The Lordof the Rings', 'isbn': '0-395-19395-8', 'price': 22.99}]

    6)输出book节点中所有价格小于10的对象:

    checkurl="$.store.book[?(@.price<10)]"
    books = jsonpath.jsonpath(books, checkurl)
    print(books)
    # 输出: [{&#39;category&#39;: &#39;reference&#39;, &#39;author&#39;: &#39;Nigel Rees&#39;, &#39;title&#39;:&#39;Sayings of the Century&#39;, &#39;price&#39;: 8.95}]

    7)输出book节点中所有含有isb的对象:

    checkurl = "$.store.book[?(@.isb)]"
    books = jsonpath.jsonpath(books,checkurl)
    print(books)
    # 输出: [{&#39;category&#39;: &#39;fiction&#39;, &#39;author&#39;: &#39;J. R. R. Tolkien&#39;, &#39;title&#39;: &#39;The Lord of the Rings&#39;, &#39;isbn&#39;: &#39;0-395-19395-8&#39;, &#39;price&#39;: 22.99}]

    以上是Python Json读写操作之JsonPath怎么使用的详细内容。更多信息请关注PHP中文网其他相关文章!

    声明:
    本文转载于:yisu.com。如有侵权,请联系admin@php.cn删除