教育行業(yè)A股IPO第一股(股票代碼 003032)

全國咨詢/投訴熱線:400-618-4000

JsonPath基本語法介紹:JsonPath用法詳解

更新時間:2021年05月27日14時36分 來源:傳智教育 瀏覽次數(shù):

好口碑IT培訓

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

JSONPath的安裝方法如下:

pip install jsonpath
JSONPath語法和XPATH語法對比 JSON結構清晰,可讀性高,復雜度低,非常容易匹配。JSONPath的語法與Xpath類似,如下表所示為JSONPath與XPath語法對比。
XPATH JSONPATH 描述
/ $ 根節(jié)點
. @ 現(xiàn)行節(jié)點
/ .or[] 取子節(jié)點  
.. n/a 取父節(jié)點,JSONPath未支持
// .. 不管位置,選擇所有符合條件的節(jié)點
* * 匹配所有元素節(jié)點
@ n/a 根據(jù)屬性訪問,JSON不支持,因為JSON是個key-value遞歸結構,不需要屬性訪問
[] [] 迭代器標示(可以在里面做簡單的迭代操作,如數(shù)組下標、根據(jù)內容選值等)
| [,] 支持迭代器中做多選
[] ?() 支持過濾操作
n/a () 分組,JSONPath不支持

下面使用一個JSON文檔演示JSONPath的具體使用。JSON 文檔的內容如下:

{
  "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中已經(jīng)包含了這段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}]



猜你喜歡:

python中for循環(huán)的用法

Python os.listdir()方法的用法

Python requests模塊是做什么的?

Python中的字典是什么?怎么通過字典查詢信息?

傳智教育Python+大數(shù)據(jù)培訓課程

0 分享到:
和我們在線交談!