一、什麼是JsonPath?
1、JsonPath是什麼?JsonPath是一種表達式語言,用於解析JSON數據中的屬性。
2、JsonPath依照XPath語法規則來構建,使用JsonPath可以方便地從JSON數據中提取所需的信息,類似於XPath從XML文檔中提取所需信息的功能。
3、JsonPath是一種允許開發者在JSON文檔中查找數據的表達式語言,它更像是一種DSL。
二、JsonPath語法規則
1、JsonPath可以解析類似於XPath的語法規則,例如:$代表根節點;.代表層級關係;[]代表索引或下標;*代表通配符。
2、JsonPath的表達式可以是對象屬性、數組範圍、數組元素或者通配符。
3、JsonPath支持標量值,也支持對象和數組,當JsonPath求值為標量值時,它的結果將是一個簡單數據類型,例如字元串或數字,當JsonPath求值為一個對象或數組時,它的結果將是一個JSON格式的對象。
三、JsonPath的用法示例
1、獲取JSON對象中的一級屬性
{ "name": "JsonPath", "version": "1.0.0", "author": { "name": "Tom", "age": 26 } } $.name
上述示例結果為:”JsonPath”,即獲取JSON對象中的一級屬性。
2、獲取JSON對象中的多級屬性
{ "name": "JsonPath", "version": "1.0.0", "author": { "name": "Tom", "age": 26 } } $.author.name
上述示例結果為:”Tom”,即獲取JSON對象中的多級屬性。
3、獲取JSON對象中的數組元素
{ "fruits": [ { "name": "watermelon", "price": 2.5 }, { "name": "apple", "price": 1.5 }, { "name": "banana", "price": 2 } ] } $.fruits[1]
上述示例結果為:{“name”: “apple”, “price”: 1.5},即獲取JSON對象中的數組元素。
4、獲取JSON對象中的多個數組元素
{ "fruits": [ { "name": "watermelon", "price": 2.5 }, { "name": "apple", "price": 1.5 }, { "name": "banana", "price": 2 } ] } $.fruits[0,2]
上述示例結果為:[{“name”: “watermelon”, “price”: 2.5}, {“name”: “banana”, “price”: 2}],即獲取JSON對象中的多個數組元素。
5、獲取JSON對象中滿足條件的數組元素
{ "fruits": [ { "name": "watermelon", "price": 2.5 }, { "name": "apple", "price": 1.5 }, { "name": "banana", "price": 2 } ] } $.fruits[?(@.name=='apple')]
上述示例結果為:[{“name”: “apple”, “price”: 1.5}],即獲取JSON對象中滿足條件的數組元素。
6、獲取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 } ], "bicycle": { "color": "red", "price": 19.95 } } } $..book[0].title
上述示例結果為:”Sayings of the Century”,即獲取JSON對象中的嵌套屬性。
四、 JsonPath在線解析工具推薦
1、JsonPath Online Evaluator( https://jsonpath.com/ ),它提供了JsonPath在線解析的功能,支持JsonPath語法規則,已經支持了許多其他語言的API綁定。
2、JsonPath Playground( http://jsonpath.herokuapp.com/ ),它是一個可在線測試JsonPath表達式的應用,用戶可以輸入待測試的JSON數據,輸入JsonPath表達式後,可以查看解析結果和執行時間,同時還支持前端JSLib實驗室。
五、總結
以上是關於JsonPath在線解析的詳細闡述,其中詳細講解了JsonPath的語法規則及用法示例,此外,還介紹了兩款常用的JsonPath在線解析工具,並且推薦了JsonPath Playground本文的使用,相信讀者能夠快速上手學會JsonPath的使用。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/293187.html