? ? JSON全稱為JavaScript Object Notation,一般翻譯為JS標(biāo)記,是一種輕量級的數(shù)據(jù)交換格式。是基于ECMAScript的一個子集,采用完全獨立于編程語言的文本格式來存儲和表示數(shù)據(jù)。簡潔和清晰的層次結(jié)構(gòu)使得JSON成為理想的數(shù)據(jù)交換語言,其主要特點有:易于閱讀、易于機器生成、有效提升網(wǎng)絡(luò)速度等。
創(chuàng)新互聯(lián)建站專業(yè)為企業(yè)提供信宜網(wǎng)站建設(shè)、信宜做網(wǎng)站、信宜網(wǎng)站設(shè)計、信宜網(wǎng)站制作等企業(yè)網(wǎng)站建設(shè)、網(wǎng)頁設(shè)計與制作、信宜企業(yè)網(wǎng)站模板建站服務(wù),十年信宜做網(wǎng)站經(jīng)驗,不只是建網(wǎng)站,更提供有價值的思路和整體網(wǎng)絡(luò)服務(wù)。
? ? JSON簡單來說,可以理解為JavaScript中的數(shù)組和對象,通過這兩種結(jié)構(gòu),可以表示各種復(fù)雜的結(jié)構(gòu)。
? ? 數(shù)組在JavaScript是使用中括號[ ]來定義的,一般定義格式如下所示:
let array=["Surpass","28","Shanghai"];
? ? 若要對數(shù)組取值,則需要使用索引。元素的類型可以是數(shù)字、字符串、數(shù)組和對象等。
? ? 對象在JavaScript是使用大括號{ }來定義的,一般定義格式如下所示:
let personInfo={
name:"Surpass",
age:28,
location:"Shanghai"
}
? ? 對象一般是基于key和value,在JavaScript中,其取值方式也非常簡單variable.key即可。元素value的類型可以是數(shù)字、字符串、數(shù)組和對象等。
? ? JSON支持的主要數(shù)據(jù)格式如下所示:
? ? 多個數(shù)據(jù)之間使用逗號做為分隔符,基與Python中的數(shù)據(jù)類型對應(yīng)表如下所示:
JSON | Python |
---|---|
Object | dict |
array | list |
string | str |
number(int) | int |
number(real) | float |
true | True |
false | False |
null | None |
? ? 在Python中主要使用json模塊來對JSON數(shù)據(jù)進行處理。在使用前,需要導(dǎo)入json模塊,用法如下所示:
import json
? ? json模塊中主要包含以下四個操作函數(shù),如下所示:
? ? 在json的處理過種中,Python中的原始類型與JSON類型會存在相互轉(zhuǎn)換,具體的轉(zhuǎn)換表如下所示:
Python | JSON |
---|---|
dict | Object |
list | array |
tuple | array |
str | string |
int | number |
float | number |
True | true |
False | false |
None | null |
JSON | Python |
---|---|
Object | dict |
array | list |
string | str |
number(int) | int |
number(real) | float |
true | True |
false | False |
null | None |
? ? 關(guān)于Python 內(nèi)置的json模塊,可以查看之前我寫的文章:https://www.cnblogs.com/surpassme/p/.html
? ? 內(nèi)置的json模塊,在處理簡單的JSON數(shù)據(jù)時,易用且非常非常方便,但在處理比較復(fù)雜且特別大的JSON數(shù)據(jù),還是有一些費力,今天我們使用一個第三方的工具來處理JSON數(shù)據(jù),叫JSONPath。
? ? JSONPath是一種用于解析JSON數(shù)據(jù)的表達語言。經(jīng)常用于解析和處理多層嵌套的JSON數(shù)據(jù),其用法與解析XML數(shù)據(jù)的XPath表達式語言非常相似。
? ? 安裝方法如下所示:
# pip install -U jsonpath
? ? JSONPath語法與XPath非常相似,其對應(yīng)參照表如下所示:
XPath | JSONPath | 描述 |
---|---|---|
/ | $ | 根節(jié)點/元素 |
. | @ | 當(dāng)前節(jié)點/元素 |
/ | . or [] | 子元素 |
.. | n/a | 父元素 |
// | .. | 遞歸向下搜索子元素 |
* | * | 通配符,表示所有元素 |
@ | n/a | 訪問屬性,JSON結(jié)構(gòu)的數(shù)據(jù)沒有這種屬性 |
[] | [] | 子元素操作符(可以在里面做簡單的迭代操作,如數(shù)據(jù)索引,根據(jù)內(nèi)容選值等) |
| | [,] | 支持迭代器中做多選 |
n/a | [start :end :step] | 數(shù)組分割操作 |
[] | ?() | 篩選表達式 |
n/a | () | 支持表達式計算 |
() | n/a | 分組,JSONPath不支持 |
以上內(nèi)容可查閱官方文檔:https://goessner.net/articles/JsonPath/
? ? 我們以下示例數(shù)據(jù)為例,來進行對比,如下所示:
{ "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--3",
"price": 8.99
},
{ "category": "fiction",
"author": "J. R. R. Tolkien",
"title": "The Lord of the Rings",
"isbn": "0-395--8",
"price": 22.99
}
],
"bicycle": {
"color": "red",
"price": 19.95
}
}
}
XPath | JSONPath | 結(jié)果 |
---|---|---|
/store/book/author | $.store.book[*].author | 獲取book節(jié)點中所有author |
//author | $..author | 獲取所有author |
/store/* | $.store.* | 獲取store的元素,包含book和bicycle |
/store//price | $.store..price | 獲取store中的所有price |
//book[3] | $..book[2] | 獲取第三本書所有信息 |
//book[last()] | $..book[(@.length-1)] $..book[-1:] |
獲取最后一本書的信息 |
//book[position()??] | $..book[0,1] $..book[:2] |
獲取前面的兩本書 |
//book[isbn] | $..book[?(@.isbn)] | 根據(jù)isbn進行過濾 |
//book[price<10] | $..book[?(@.price<10)] | 根據(jù)price進行篩選 |
//* | $..* | 所有元素 |
在XPath中,下標(biāo)是1開始,而在JSONPath中是從0開始
JSONPath在線練習(xí)網(wǎng)址:http://jsonpath.com/
? ? 其基本用法形式如下所示:
jsonPath(obj, expr [, args])
? ? 基參數(shù)如下所示:
? ? JSON數(shù)據(jù)對象
? ? JSONPath表達式
? ? 改變輸出格式,比如是輸出是值還是路徑,
args.resultType可選的輸出格式為:"VALUE"、"PATH"、"IPATH"
? ? 若返回array,則代表成功匹配到數(shù)據(jù),false則代表未匹配到數(shù)據(jù)。
from jsonpath import jsonpath
import json
data = {
"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--3",
"price": 8.99
},
{
"category": "fiction",
"author": "J. R. R. Tolkien",
"title": "The Lord of the Rings",
"isbn": "0-395--8",
"price": 22.99
}
],
"bicycle": {
"color": "red",
"price": 19.95
}
}
}
# 獲取book節(jié)點中所有author
getAllBookAuthor=jsonpath(data,"$.store.book[*].author")
print(f"getAllBookAuthor is :{json.dumps(getAllBookAuthor,indent=4)}")
# 獲取book節(jié)點中所有author
getAllAuthor=jsonpath(data,"$..author")
print(f"getAllAuthor is {json.dumps(getAllAuthor,indent=4)}")
# 獲取store的元素,包含book和bicycle
getAllStoreElement=jsonpath(data,"$.store.*")
print(f"getAllStoreElement is {json.dumps(getAllStoreElement,indent=4)}")
# 獲取store中的所有price
getAllStorePriceA=jsonpath(data,"$[store]..price")
getAllStorePriceB=jsonpath(data,"$.store..price")
print(f"getAllStorePrictA is {getAllStorePriceA}\ngetAllStorePriceB is {getAllStorePriceB}")
# 獲取第三本書所有信息
getThirdBookInfo=jsonpath(data,"$..book[2]")
print(f"getThirdBookInfo is {json.dumps(getThirdBookInfo,indent=4)}")
# 獲取最后一本書的信息
getLastBookInfo=jsonpath(data,"$..book[-1:]")
print(f"getLastBookInfo is {json.dumps(getLastBookInfo,indent=4)}")
# 獲取前面的兩本書
getFirstAndSecondBookInfo=jsonpath(data,"$..book[:2]")
print(f"getFirstAndSecondBookInfo is {json.dumps(getFirstAndSecondBookInfo,indent=4)}")
# 根據(jù)isbn進行過濾
getWithFilterISBN=jsonpath(data,"$..book[?(@.isbn)]")
print(f"getWithFilterISBN is {json.dumps(getWithFilterISBN,indent=4)}")
# 根據(jù)price進行篩選
getWithFilterPrice=jsonpath(data,"$..book[?(@.price<10)]")
print(f"getWithFilterPrice is {json.dumps(getWithFilterPrice,indent=4)}")
# 所有元素
getAllElement=jsonpath(data,"$..*")
print(f"getAllElement is {json.dumps(getAllElement,indent=4)}")
# 未能匹配到元素時
noMatchElement=jsonpath(data,"$..surpass")
print(f"noMatchElement is {noMatchElement}")
# 調(diào)整輸出格式
controlleOutput=jsonpath(data,expr="$..author",result_type="PATH")
print(f"controlleOutput is {json.dumps(controlleOutput,indent=4)}")
? ? 最終輸出結(jié)果如下?lián)P塵:
getAllBookAuthor is :[
"Nigel Rees",
"Evelyn Waugh",
"Herman Melville",
"J. R. R. Tolkien"
]
getAllAuthor is [
"Nigel Rees",
"Evelyn Waugh",
"Herman Melville",
"J. R. R. Tolkien"
]
getAllStoreElement is [
[
{
"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--3",
"price": 8.99
},
{
"category": "fiction",
"author": "J. R. R. Tolkien",
"title": "The Lord of the Rings",
"isbn": "0-395--8",
"price": 22.99
}
],
{
"color": "red",
"price": 19.95
}
]
getAllStorePrictA is [8.95, 12.99, 8.99, 22.99, 19.95]
getAllStorePriceB is [8.95, 12.99, 8.99, 22.99, 19.95]
getThirdBookInfo is [
{
"category": "fiction",
"author": "Herman Melville",
"title": "Moby Dick",
"isbn": "0-553--3",
"price": 8.99
}
]
getLastBookInfo is [
{
"category": "fiction",
"author": "J. R. R. Tolkien",
"title": "The Lord of the Rings",
"isbn": "0-395--8",
"price": 22.99
}
]
getFirstAndSecondBookInfo is [
{
"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
}
]
getWithFilterISBN is [
{
"category": "fiction",
"author": "Herman Melville",
"title": "Moby Dick",
"isbn": "0-553--3",
"price": 8.99
},
{
"category": "fiction",
"author": "J. R. R. Tolkien",
"title": "The Lord of the Rings",
"isbn": "0-395--8",
"price": 22.99
}
]
getWithFilterPrice is [
{
"category": "reference",
"author": "Nigel Rees",
"title": "Sayings of the Century",
"price": 8.95
},
{
"category": "fiction",
"author": "Herman Melville",
"title": "Moby Dick",
"isbn": "0-553--3",
"price": 8.99
}
]
getAllElement is [
{
"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--3",
"price": 8.99
},
{
"category": "fiction",
"author": "J. R. R. Tolkien",
"title": "The Lord of the Rings",
"isbn": "0-395--8",
"price": 22.99
}
],
"bicycle": {
"color": "red",
"price": 19.95
}
},
[
{
"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--3",
"price": 8.99
},
{
"category": "fiction",
"author": "J. R. R. Tolkien",
"title": "The Lord of the Rings",
"isbn": "0-395--8",
"price": 22.99
}
],
{
"color": "red",
"price": 19.95
},
{
"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--3",
"price": 8.99
},
{
"category": "fiction",
"author": "J. R. R. Tolkien",
"title": "The Lord of the Rings",
"isbn": "0-395--8",
"price": 22.99
},
"reference",
"Nigel Rees",
"Sayings of the Century",
8.95,
"fiction",
"Evelyn Waugh",
"Sword of Honour",
12.99,
"fiction",
"Herman Melville",
"Moby Dick",
"0-553--3",
8.99,
"fiction",
"J. R. R. Tolkien",
"The Lord of the Rings",
"0-395--8",
22.99,
"red",
19.95
]
noMatchElement is False
controlleOutput is [
"$['store']['book'][0]['author']",
"$['store']['book'][1]['author']",
"$['store']['book'][2]['author']",
"$['store']['book'][3]['author']"
]
原文地址:https://www.jianshu.com/p/a69a9cf293bd
本文同步在微信訂閱號上發(fā)布,如各位小伙伴們喜歡我的文章,也可以關(guān)注我的微信訂閱號:woaitest,或掃描下面的二維碼添加關(guān)注: