JsonPath基本用法
- 2019 年 10 月 6 日
- 筆記
JsonPath基本用法
本文主要介紹JsonPath的基本語法,並演示如何在Newtonsoft.Json中進行使用。
JsonPath的來源
看它的名字你就能知道,這傢伙和JSON文檔有關係,正如XPath之於XML文檔一樣,JsonPath為Json文檔提供了解析能力,通過使用JsonPath,你可以方便的查找節點、獲取想要的數據,JsonPath是Json版的XPath。
JsonPath語法
JsonPath的語法相對簡單,它採用開發語言友好的表達式形式,如果你了解類C語言,對JsonPath就不會感到不適應。
JsonPath語法要點:
$
表示文檔的根元素@
表示文檔的當前元素.node_name
或['node_name']
匹配下級節點[index]
檢索數組中的元素[start:end:step]
支援數組切片語法*
作為通配符,匹配所有成員..
子遞歸通配符,匹配成員的所有子元素(<expr>)
使用表達式?(<boolean expr>)
進行數據篩選
下表將列舉所有支援的語法,並對XPath進行比較:
XPath |
JsonPath |
說明 |
---|---|---|
/ |
$ |
文檔根元素 |
. |
@ |
當前元素 |
/ |
.或[] |
匹配下級元素 |
.. |
N/A |
匹配上級元素,JsonPath不支援此操作符 |
// |
.. |
遞歸匹配所有子元素 |
* |
* |
通配符,匹配下級元素 |
@ |
N/A |
匹配屬性,JsonPath不支援此操作符 |
[] |
[] |
下標運算符,根據索引獲取元素,XPath索引從1開始,JsonPath索引從0開始 |
| |
[,] |
連接操作符,將多個結果拼接成數組返回,可以使用索引或別名 |
N/A |
[start:end:step] |
數據切片操作,XPath不支援 |
[] |
?() |
過濾表達式 |
N/A |
() |
腳本表達式,使用底層腳本引擎,XPath不支援 |
() |
N/A |
分組,JsonPath不支援 |
注意:
- JsonPath的索引從0開始計數
- JsonPath中字元串使用單引號表示,例如:
$.store.book[?(@.category=='reference')]
中的'reference'
JsonPath示例
下面是相應的JsonPath的示例,程式碼來源於https://goessner.net/articles/JsonPath/,JSON文檔如下:
{ "store": { "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 } } }
接下來我們看一下如何對這個文檔進行解析:
XPath |
JsonPath |
Result |
---|---|---|
/store/book/author |
$.store.book[*].author |
所有book的author節點 |
//author |
$..author |
所有author節點 |
/store/* |
$.store.* |
store下的所有節點,book數組和bicycle節點 |
/store//price |
$.store..price |
store下的所有price節點 |
//book[3] |
$..book[2] |
匹配第3個book節點 |
//book[last()] |
$..book[(@.length-1)],或 $..book[-1:] |
匹配倒數第1個book節點 |
//book[position()<3] |
$..book[0,1],或 $..book[:2] |
匹配前兩個book節點 |
//book[isbn] |
$..book[?(@.isbn)] |
過濾含isbn欄位的節點 |
//book[price<10] |
$..book[?(@.price<10)] |
過濾price<10的節點 |
//* |
$..* |
遞歸匹配所有子節點 |
你可以在http://jsonpath.com/站點進行驗證JsonPath的執行效果。
在Newtonsoft.Json中的用法
JsonPath是語言無關的表達式語言,Newtonsoft.Json庫提供了對JsonPath的支援,它提供了JObject.SelectToken()
和JObject.SelectTokens()
方法來使用JsonPath解析Json文檔,程式碼如下:
//創建JObject對象 var jObj = JObject.Parse(jsonString); var books = jObj.SelectToken("$.store.book[?(@.category=='reference')]");
參考文檔: