在python中使用Json提取數(shù)據(jù)的詳細(xì)過(guò)程
一、前言
官方文檔:https://docs.python.org/zh-cn/3.12/library/json.html
在Python中,json模塊可以方便地處理JSON數(shù)據(jù)與Python對(duì)象之間的轉(zhuǎn)換。然而,如果僅用json模塊來(lái)提取特定數(shù)據(jù),就有點(diǎn)力不從心了,這時(shí)可以使用JSONPath模塊,但它的操作稍顯復(fù)雜,那么JMESPath模塊就是不錯(cuò)的選擇
二、格式轉(zhuǎn)換
python的json模塊用于處理Json數(shù)據(jù),Json字符串與python類型之間的轉(zhuǎn)換關(guān)系如下圖所示:

2.1 dumps函數(shù)
函數(shù)格式:json.dumps(obj, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)
參數(shù)解析:以下是一些常用的參數(shù),更多參數(shù)參考:https://docs.python.org/zh-cn/3/library/json.html#basic-usage
| 常用參數(shù) | 描述 |
|---|---|
| indent | 美化輸出 |
| ensure_ascii | 為False時(shí)可保留非ASCII字符(如中文) |
| sort_keys | 為True時(shí)按鍵名排序輸出 |
使用示例:
import json
mydict={'name':'張三','age':15}
json_str = json.dumps(mydict, indent=2, ensure_ascii=False)
print(json_str)
print(type(json_str)) # <class 'str'>
2.2 loads函數(shù)
函數(shù)格式:json.loads(s, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)</font>**
具體參數(shù)參考:https://docs.python.org/zh-cn/3/library/json.html#basic-usage
使用示例:以百度翻譯為例
import json
import requests
url = "https://fanyi.baidu.com/sug"
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36 Edg/109.0.1518.78"
}
data = {
"kw": "face to face"
}
response = requests.post(url=url, data=data, headers=headers)
result = json.loads(response.text)
# result = response.json()
for item in result["data"]:
print(item["k"], item["v"])
2.3 錯(cuò)誤處理
捕獲JSON解析錯(cuò)誤:exception json.JSONDecodeError(msg, doc, pos),JSONDecodeError有msg錯(cuò)誤信息、doc正在解析的JSON文檔、pos文檔中解析失敗的起始位置索引等屬性。
try:
data = json.loads(invalid_json_str)
except json.JSONDecodeError as e:
print(f"解析失敗: {e}")
三、JSONPath模塊
官方文檔:https://goessner.net/articles/JsonPath/
JSONPath模塊可以對(duì)JSON 數(shù)據(jù)快速提取,安裝:pip install jsonpath-ng
他與XPath語(yǔ)法相似:

以下面數(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-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
}
}
}
使用JSONPath獲取數(shù)據(jù):

代碼實(shí)現(xiàn)
from jsonpath_ng import parse
# 定義 JSONPath 表達(dá)式
expr = parse("$.store.book[*].title")
# 提取數(shù)據(jù)
matches = [match.value for match in expr.find(data)]
print(matches)
# 輸出: ['Sayings of the Century', 'Sword of Honour', 'Moby Dick', 'The Lord of the Rings']
四、JMESPath模塊
官方文檔:https://jmespath.org/tutorial.html
相比于JSONPath,JMESPath語(yǔ)法更簡(jiǎn)潔,性能更好,安裝:pip install jmespath
根據(jù)上述例子,則有:
import jmespath
# 提取所有書籍標(biāo)題
result = jmespath.search("store.book[*].title", data)
print(result)
# 輸出: ['Sayings of the Century', 'Sword of Honour', 'Moby Dick', 'The Lord of the Rings']
具體使用參見下文
4.1 search函數(shù)
jmespath.search是 JMESPath 庫(kù)的核心函數(shù),用于在 JSON 數(shù)據(jù)中執(zhí)行查詢表達(dá)式并返回匹配結(jié)果,格式為jmespath.search(expression, data),更多參考https://jmespath.org/specification.html
expression:JMESPath 查詢字符串(如"users[*].name")
data:待查詢的 JSON 數(shù)據(jù)(Python 字典或列表)
查詢成功則返回匹配的數(shù)據(jù),否則返回None
對(duì)于要重復(fù)執(zhí)行的查詢,可以預(yù)編譯
from jmespath import compile as jmes_compile
# 預(yù)編譯表達(dá)式
expr = jmes_compile("users[*].name")
# 多次使用編譯后的表達(dá)式
result1 = expr.search(data1)
result2 = expr.search(data2)
在錯(cuò)誤處理上,可以用try-except捕獲jmespath.exceptions.JMESPathError
try:
result = jmespath.search("invalid.expression[", data)
except jmespath.exceptions.JMESPathError as e:
print(f"表達(dá)式錯(cuò)誤: {e}")
4.2 基本語(yǔ)法
4.2.1 基本查詢
基本表達(dá)式:JSON對(duì)象中的一個(gè)鍵,如果不存在則返回null


相應(yīng)的代碼實(shí)現(xiàn):
#自定義環(huán)境 library/python:3.9-slim-top1000
import jmespath
data = {"a": "foo", "b": "bar", "c": "baz"}
result = jmespath.search("a", data)
print(result) # 輸出: foo
支持索引訪問(wèn),從0開始,也支持負(fù)索引(從列表末尾開始索引)


使用.訪問(wèn)子節(jié)點(diǎn):


支持切片,與python的切片類似,格式為[start:stop:step]


4.2.2 投影
投影,是jmespath的一個(gè)關(guān)鍵特性,允許將一個(gè)表達(dá)式應(yīng)用于一組元素,有五種類型:
- List Projections:列表投影
- Slice Projections:切片投影
- Object Projections:對(duì)象投影
- Flatten Projections:平坦投影
- Filter Projections:過(guò)濾投影
列表投影:僅適用于列表,*用來(lái)匹配列表中所有元素或?qū)ο蟮乃墟I;[]用于列表投影,類似于SQL中的SELECT
{"missing": "different"} 在應(yīng)用表達(dá)式first時(shí)評(píng)估為null,并且null值不會(huì)被添加到收集結(jié)果數(shù)組中

也可以提取多個(gè)字段組成多個(gè)列表

切片投影:與列表投影幾乎相同,區(qū)別在于左側(cè)是切片評(píng)估的結(jié)果,

對(duì)象投影:從對(duì)象中提取多個(gè)字段,生成新的字典或列表

展平投影:將嵌套的列表結(jié)構(gòu)轉(zhuǎn)換為單層列表,便于處理多層嵌套數(shù)據(jù),列表[]將嵌套列表展平,通常結(jié)合*使用

如果元素不是列表,展平操作會(huì)忽略它

過(guò)濾投影:使用過(guò)濾表達(dá)式[?條件]實(shí)現(xiàn)更精準(zhǔn)的數(shù)據(jù)提取,過(guò)濾表達(dá)式支持比較運(yùn)算符(==、!=、<、<=、>、>=)、邏輯運(yùn)算符

4.2.3 管道
使用管道表達(dá)式<expression> | <expression>來(lái)表示投影必須停止。當(dāng)遇到管道符時(shí),該點(diǎn)之前的結(jié)果會(huì)被傳遞給管道表達(dá)式的右側(cè)

4.2.4 多選
同時(shí)提取多個(gè)字段,返回字典或列表;多選與投影不同,即使表達(dá)式結(jié)果為空,也會(huì)包含在內(nèi)
- 哈希多選:
{key1: expr1, key2: expr2}
- 列表多選:
[expr1, expr2]

4.2.5 函數(shù)
支持函數(shù)表達(dá)式,更多參考:https://jmespath.org/specification.html#functions
| 常用函數(shù) | 描述 |
|---|---|
length() | 計(jì)算長(zhǎng)度(字符串、列表、字典) |
keys()/values() | 獲取字典的鍵或值 |
sort() | 排序列表 |
join() | 連接字符串列表 |
to_array()/to_object() | 轉(zhuǎn)換類型 |

總結(jié)
到此這篇關(guān)于在python中使用Json提取數(shù)據(jù)的文章就介紹到這了,更多相關(guān)python用Json提取數(shù)據(jù)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python使用in操作符時(shí)元組和數(shù)組的區(qū)別分析
有時(shí)候要判斷一個(gè)數(shù)是否在一個(gè)序列里面,這時(shí)就會(huì)用到in運(yùn)算符來(lái)判斷成員資格,如果條件為真時(shí),就會(huì)返回true,條件為假時(shí),返回一個(gè)flase。這樣的運(yùn)算符叫做布爾運(yùn)算符,其真值叫做布爾值。2015-05-05
python numpy.ndarray中如何將數(shù)據(jù)轉(zhuǎn)為int型
這篇文章主要介紹了python numpy.ndarray中如何將數(shù)據(jù)轉(zhuǎn)為int型,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-05-05
python機(jī)器基礎(chǔ)邏輯回歸與非監(jiān)督學(xué)習(xí)
這篇文章主要為大家介紹了python機(jī)器基礎(chǔ)邏輯回歸與非監(jiān)督的學(xué)習(xí)講解u,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步2021-11-11
python2.7使用plotly繪制本地散點(diǎn)圖和折線圖
這篇文章主要為大家詳細(xì)介紹了python2.7使用plotly繪制本地散點(diǎn)圖和折線圖實(shí)例,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-04-04

