在 Python 中俐镐,讀取和解析 JSON 數(shù)據(jù)是一項(xiàng)非常常見(jiàn)的任務(wù)。JSON 格式(JavaScript Object Notation)是一種輕量級(jí)的數(shù)據(jù)交換格式梆砸,易于人類閱讀和編寫转质,同時(shí)易于機(jī)器解析和生成。Python 內(nèi)置的 json
模塊可以輕松地處理 JSON 數(shù)據(jù)帖世,無(wú)論是從文件中讀取 JSON休蟹,還是從字符串中解析 JSON,都是相當(dāng)直接的日矫。
json
模塊的基本功能
json
模塊提供了一些核心函數(shù):
-
json.load(f)
:從文件對(duì)象f
中讀取并解析 JSON 數(shù)據(jù)赂弓。 -
json.loads(s)
:從字符串s
中解析 JSON 數(shù)據(jù)。 -
json.dump(obj, f)
:將 Python 對(duì)象obj
寫入到文件f
中哪轿,作為 JSON 格式的數(shù)據(jù)盈魁。 -
json.dumps(obj)
:將 Python 對(duì)象obj
轉(zhuǎn)換為 JSON 格式的字符串。
讀取和解析 JSON 數(shù)據(jù)的基本步驟
為了展示如何使用 json
模塊讀取和解析 JSON 數(shù)據(jù)窃诉,我們可以用一個(gè)簡(jiǎn)單的例子來(lái)說(shuō)明如何從文件中讀取 JSON 數(shù)據(jù)并解析成 Python 對(duì)象杨耙。假設(shè)我們有一個(gè)名為 data.json
的文件赤套,內(nèi)容如下:
{
"name": "John",
"age": 30,
"city": "New York",
"children": [
{
"name": "Jane",
"age": 10
},
{
"name": "Doe",
"age": 8
}
]
}
這個(gè)文件存儲(chǔ)了一個(gè)人的基本信息,其中包括他的名字按脚、年齡于毙、城市以及兩個(gè)孩子的信息。接下來(lái)我們會(huì)用 Python 來(lái)讀取這個(gè)文件辅搬,并解析其內(nèi)容唯沮。
示例代碼:從文件讀取 JSON 數(shù)據(jù)并解析
以下是讀取 data.json
文件并解析其內(nèi)容的完整 Python 代碼示例:
import json
# 定義要讀取的文件路徑
file_path = 'data.json'
# 打開并讀取文件內(nèi)容
with open(file_path, 'r', encoding='utf-8') as file:
data = json.load(file)
# 輸出解析后的數(shù)據(jù)
print(data)
# 訪問(wèn) JSON 數(shù)據(jù)中的各個(gè)字段
print(f"Name: {data['name']}")
print(f"Age: {data['age']}")
print(f"City: {data['city']}")
# 遍歷孩子的信息
for child in data['children']:
print(f"Child Name: {child['name']}, Age: {child['age']}")
代碼分析
-
import json
:導(dǎo)入json
模塊,它是處理 JSON 數(shù)據(jù)的核心工具堪遂。 -
with open(file_path, 'r', encoding='utf-8') as file
:使用with
語(yǔ)句打開文件介蛉,這是一種 Python 中常見(jiàn)的文件操作模式,保證文件會(huì)在操作結(jié)束后自動(dòng)關(guān)閉溶褪。我們以utf-8
編碼讀取文件币旧,以防止編碼問(wèn)題。 -
json.load(file)
:將文件對(duì)象傳遞給json.load()
函數(shù)猿妈,讀取并解析文件內(nèi)容為 Python 的字典或列表吹菱。 -
print(data)
:輸出整個(gè)解析后的 JSON 數(shù)據(jù),它現(xiàn)在是一個(gè) Python 的字典彭则。 - 通過(guò)
data['name']
,data['age']
等方式訪問(wèn) JSON 對(duì)象的字段鳍刷。這是字典的典型操作方式。 - 使用
for
循環(huán)遍歷data['children']
俯抖,訪問(wèn)孩子的信息输瓜。
解析 JSON 字符串
有時(shí)候 JSON 數(shù)據(jù)可能直接以字符串的形式提供,而不是存儲(chǔ)在文件中芬萍。我們可以使用 json.loads()
來(lái)解析字符串形式的 JSON 數(shù)據(jù)尤揣。
假設(shè)我們有一個(gè) JSON 字符串:
json_string = '{"name": "Alice", "age": 25, "city": "London"}'
我們可以使用以下代碼解析這個(gè)字符串:
import json
# 定義 JSON 字符串
json_string = '{"name": "Alice", "age": 25, "city": "London"}'
# 解析 JSON 字符串
data = json.loads(json_string)
# 輸出解析后的數(shù)據(jù)
print(data)
# 訪問(wèn)數(shù)據(jù)中的字段
print(f"Name: {data['name']}")
print(f"Age: {data['age']}")
print(f"City: {data['city']}")
這段代碼與從文件讀取的方式非常類似,只是這里我們將 JSON 字符串直接傳遞給 json.loads()
函數(shù)柬祠。
JSON 寫入文件
Python 也可以很方便地將數(shù)據(jù)寫入到 JSON 文件中北戏,使用 json.dump()
函數(shù)可以將 Python 對(duì)象轉(zhuǎn)換為 JSON 格式并寫入文件。假設(shè)我們有以下 Python 數(shù)據(jù):
person = {
"name": "Bob",
"age": 40,
"city": "Chicago",
"children": [
{
"name": "Anna",
"age": 12
},
{
"name": "Tom",
"age": 7
}
]
}
我們可以將這個(gè)數(shù)據(jù)寫入到 output.json
文件中瓶盛,代碼如下:
import json
# 定義 Python 對(duì)象
person = {
"name": "Bob",
"age": 40,
"city": "Chicago",
"children": [
{
"name": "Anna",
"age": 12
},
{
"name": "Tom",
"age": 7
}
]
}
# 將數(shù)據(jù)寫入到文件
with open('output.json', 'w', encoding='utf-8') as file:
json.dump(person, file, ensure_ascii=False, indent=4)
代碼分析
-
json.dump(person, file, ensure_ascii=False, indent=4)
:json.dump()
將 Python 對(duì)象寫入文件最欠。ensure_ascii=False
確保非 ASCII 字符能夠被正確處理,比如中文字符惩猫。indent=4
參數(shù)用于美化輸出,使得生成的 JSON 文件更易于閱讀蚜点。 - 文件會(huì)自動(dòng)寫入
output.json
中轧房,內(nèi)容格式化后的樣子如下:
{
"name": "Bob",
"age": 40,
"city": "Chicago",
"children": [
{
"name": "Anna",
"age": 12
},
{
"name": "Tom",
"age": 7
}
]
}
處理復(fù)雜的 JSON 結(jié)構(gòu)
在實(shí)際應(yīng)用中,JSON 數(shù)據(jù)的結(jié)構(gòu)可能非常復(fù)雜绍绘,嵌套多個(gè)層次的對(duì)象和數(shù)組奶镶。在這種情況下迟赃,Python 的 json
模塊依舊能夠輕松處理。例如厂镇,我們有一個(gè)包含更復(fù)雜數(shù)據(jù)結(jié)構(gòu)的 JSON:
{
"status": "success",
"data": {
"users": [
{
"id": 1,
"name": "Alice",
"emails": ["alice@example.com", "alice.work@example.com"]
},
{
"id": 2,
"name": "Bob",
"emails": ["bob@example.com"]
}
]
},
"meta": {
"count": 2
}
}
解析并提取這些復(fù)雜數(shù)據(jù)的代碼如下:
import json
# 定義要解析的 JSON 數(shù)據(jù)
json_data = '''
{
"status": "success",
"data": {
"users": [
{
"id": 1,
"name": "Alice",
"emails": ["alice@example.com", "alice.work@example.com"]
},
{
"id": 2,
"name": "Bob",
"emails": ["bob@example.com"]
}
]
},
"meta": {
"count": 2
}
}
'''
# 解析 JSON 數(shù)據(jù)
data = json.loads(json_data)
# 輸出用戶數(shù)據(jù)
for user in data['data']['users']:
print(f"User ID: {user['id']}, Name: {user['name']}")
print("Emails:")
for email in user['emails']:
print(f" {email}")
# 輸出 meta 數(shù)據(jù)
print(f"Total user count: {data['meta']['count']}")
錯(cuò)誤處理
在處理 JSON 數(shù)據(jù)時(shí)纤壁,可能會(huì)遇到格式錯(cuò)誤或數(shù)據(jù)缺失的問(wèn)題。為了讓程序更健壯捺信,我們需要在解析 JSON 時(shí)捕獲異常酌媒。json
模塊的 JSONDecodeError
異常可以幫助我們處理解析錯(cuò)誤:
import json
json_string = '{"name": "Alice", "age": 25, "city": "London"' # 缺少右括號(hào)
try:
data = json.loads(json_string)
except json.JSONDecodeError as e:
print(f"JSON Decode Error: {e}")
這里迄靠,json.loads()
試圖解析一個(gè)格式不正確的 JSON 字符串秒咨,由于缺少右括號(hào),它會(huì)拋出 JSONDecodeError
異常掌挚。通過(guò)捕獲這個(gè)異常雨席,我們可以為用戶提供更友好的錯(cuò)誤提示。
總結(jié)
無(wú)論是從文件中讀取 JSON 數(shù)據(jù)吠式,還是直接解析字符串形式的 JSON陡厘,Python 的 json
模塊都提供了極為簡(jiǎn)便的操作方式。你可以通過(guò) json.load()
從文件中讀取 JSON特占,通過(guò) json.loads()
解析 JSON 字符串糙置,并且可以用 json.dump()
和 json.dumps()
將 Python 對(duì)象轉(zhuǎn)化為 JSON 格式的數(shù)據(jù)。
通過(guò)這些示例代碼摩钙,你可以處理簡(jiǎn)單到復(fù)雜的 JSON 結(jié)構(gòu)罢低,并且可以通過(guò)異常捕獲提高程序的健壯性。