欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python Json讀寫操作之JsonPath用法詳解

 更新時間:2023年04月14日 11:42:33   作者:篤℃  
JSONPath是一種信息抽取類庫,是從JSON文檔中抽取指定信息的工具,提供多種語言實現版本,包括Javascript、Python、PHP和Java,這篇文章主要介紹了Python Json讀寫操作之JsonPath用法詳解,需要的朋友可以參考下

Python Json讀寫操作_JsonPath用法詳解

1. 介紹

JSONPath是一種信息抽取類庫,是從JSON文檔中抽取指定信息的工具,提供多種語言實現版本,包括Javascript、Python、PHP和Java。

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

JSONPath語法和XPATH語法對比,JSON結構清晰,可讀性高,復雜度低,非常容易匹配。JSONPath的語法與Xpath類似,如下表所示為JSONPath與XPath語法對比:

在這里插入圖片描述

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節(jié)點中包含的所有對象:

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

3)輸出book節(jié)點的第一個對象:

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節(jié)點中所有對象對應的屬性title值:

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

5)輸出book節(jié)點中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節(jié)點中所有價格小于10的對象:

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

7)輸出book節(jié)點中所有含有isb的對象:

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

3. 參考

【1】https://blog.csdn.net/fallenjency/article/details/123276600

到此這篇關于Python Json讀寫操作之JsonPath用法詳解的文章就介紹到這了,更多相關Python JsonPath用法內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

最新評論