Python使用json模塊讀取和寫入JSON數(shù)據(jù)
在現(xiàn)代軟件開發(fā)中,JSON(JavaScript Object Notation) 已成為最流行的數(shù)據(jù)交換格式之一。Python 提供了內(nèi)置的 json 模塊,使得我們可以方便地解析 JSON 數(shù)據(jù)(讀?。┖蜕?JSON 數(shù)據(jù)(寫入)。無論是 Web API 交互、配置文件存儲(chǔ),還是數(shù)據(jù)序列化,json 模塊都是不可或缺的工具。本文將詳細(xì)介紹 json 模塊的讀取、寫入、格式化、編碼解碼等操作,并結(jié)合實(shí)際案例展示其應(yīng)用。
1. JSON 與 Python 數(shù)據(jù)類型的映射關(guān)系
Python 的 json 模塊可以在 Python 基本數(shù)據(jù)類型和 JSON 數(shù)據(jù)類型之間相互轉(zhuǎn)換,映射關(guān)系如下:
| Python 類型 | JSON 類型 | 示例 |
|---|---|---|
| dict | object | {"name": "Alice", "age": 25} |
| list / tuple | array | ["apple", "banana", "cherry"] |
| str | string | "hello" |
| int / float | number | 42, 3.14 |
| bool | true / false | true, false |
| None | null | null |
2. 讀取 JSON 數(shù)據(jù)
Python 可以從字符串或文件中讀取 JSON 數(shù)據(jù)。
2.1 從 JSON 字符串解析
import json
json_str = '{"name": "Alice", "age": 25, "city": "New York"}'
# 將 JSON 字符串轉(zhuǎn)換為 Python 字典
data = json.loads(json_str)
print(data["name"]) # 輸出: Alice
print(type(data)) # 輸出: <class 'dict'>
json.loads() 作用:
- 輸入:JSON 格式的字符串。
- 輸出:轉(zhuǎn)換為 Python dict 對(duì)象。
2.2 從 JSON 文件讀取
假設(shè)有一個(gè) data.json 文件:
{
"name": "Bob",
"age": 30,
"skills": ["Python", "Java", "C++"]
}
使用 json.load() 讀取文件:
with open("data.json", "r", encoding="utf-8") as file:
data = json.load(file)
print(data["name"]) # 輸出: Bob
print(data["skills"]) # 輸出: ['Python', 'Java', 'C++']
json.load() 作用:
- 輸入:JSON 文件對(duì)象。
- 輸出:Python dict 對(duì)象。
3. 寫入 JSON 數(shù)據(jù)
Python 可以將數(shù)據(jù)寫入字符串或文件。
3.1 將 Python 對(duì)象轉(zhuǎn)換為 JSON 字符串
import json
data = {
"name": "Charlie",
"age": 28,
"city": "San Francisco"
}
# 將 Python 字典轉(zhuǎn)換為 JSON 字符串
json_str = json.dumps(data)
print(json_str)
print(type(json_str)) # 輸出: <class 'str'>
json.dumps() 作用:
- 輸入:Python dict、list、str 等。
- 輸出:JSON 格式的字符串。
3.2 將 Python 對(duì)象寫入 JSON 文件
import json
data = {
"name": "David",
"age": 35,
"languages": ["Python", "Go", "Rust"]
}
# 寫入 JSON 文件
with open("output.json", "w", encoding="utf-8") as file:
json.dump(data, file)
print("數(shù)據(jù)已寫入 output.json")
json.dump() 作用:
- 輸入:Python dict(或其他可序列化對(duì)象)。
- 輸出:寫入 JSON 文件。
4. JSON 格式化輸出(縮進(jìn)、排序)
默認(rèn)情況下,JSON 生成的字符串是緊湊的,不易閱讀:
data = {"name": "Eve", "age": 26, "city": "Paris"}
json_str = json.dumps(data)
print(json_str) # 輸出: {"name": "Eve", "age": 26, "city": "Paris"}
為了更清晰地輸出 JSON,可以使用 indent 參數(shù):
json_str = json.dumps(data, indent=4) print(json_str)
輸出(格式化 JSON):
{
"name": "Eve",
"age": 26,
"city": "Paris"
}
如果希望按鍵名排序:
json_str = json.dumps(data, indent=4, sort_keys=True) print(json_str)
輸出(按鍵排序):
{
"age": 26,
"city": "Paris",
"name": "Eve"
}
5. 處理 JSON 編碼與解碼(對(duì)象序列化)
如果 JSON 數(shù)據(jù)包含自定義對(duì)象,默認(rèn) json.dumps() 無法處理:
import json
from datetime import datetime
data = {"name": "Alice", "time": datetime.now()}
# 會(huì)報(bào)錯(cuò):Object of type datetime is not JSON serializable
json_str = json.dumps(data)
可以使用 default 參數(shù),將 datetime 對(duì)象轉(zhuǎn)換為字符串:
def json_serial(obj):
if isinstance(obj, datetime):
return obj.isoformat() # 轉(zhuǎn)換為 ISO 8601 時(shí)間格式
raise TypeError("Type not serializable")
json_str = json.dumps(data, default=json_serial, indent=4)
print(json_str)
示例輸出:
{
"name": "Alice",
"time": "2024-02-04T14:00:00.123456"
}
6. 處理 JSON 解析錯(cuò)誤
解析 JSON 時(shí),可能會(huì)遇到格式錯(cuò)誤:
import json
invalid_json = '{"name": "Tom", "age": 30,}' # 末尾多了逗號(hào)
try:
data = json.loads(invalid_json)
except json.JSONDecodeError as e:
print(f"JSON 解析錯(cuò)誤: {e}")
輸出:
JSON 解析錯(cuò)誤: Expecting property name enclosed in double quotes
7. JSON 讀寫的最佳實(shí)踐
讀取 JSON 時(shí)使用 try-except 捕獲異常
try:
with open("config.json", "r", encoding="utf-8") as file:
config = json.load(file)
except (FileNotFoundError, json.JSONDecodeError) as e:
print(f"錯(cuò)誤: {e}")
寫入 JSON 時(shí)使用 indent=4 讓數(shù)據(jù)更易讀
json.dump(data, file, indent=4)
處理非標(biāo)準(zhǔn)數(shù)據(jù)類型時(shí),使用 default 進(jìn)行序列化
json.dumps(data, default=json_serial)
8. 結(jié)論
| 操作 | 方法 |
|---|---|
| 從字符串讀取 JSON | json.loads(json_str) |
| 從文件讀取 JSON | json.load(file) |
| 將 Python 對(duì)象轉(zhuǎn)換為 JSON 字符串 | json.dumps(obj) |
| 將 Python 對(duì)象寫入 JSON 文件 | json.dump(obj, file) |
| 格式化 JSON(縮進(jìn)) | json.dumps(obj, indent=4) |
| 解析錯(cuò)誤處理 | json.JSONDecodeError |
| 處理非標(biāo)準(zhǔn)數(shù)據(jù)類型 | default=json_serial |
Python 的 json 模塊提供了強(qiáng)大且易用的 JSON 處理能力,合理使用這些方法,可以讓你的代碼更加高效、可維護(hù)!
以上就是Python使用json模塊讀取和寫入JSON數(shù)據(jù)的詳細(xì)內(nèi)容,更多關(guān)于Python讀取和寫入JSON數(shù)據(jù)的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
關(guān)于matplotlib及相關(guān)cmap參數(shù)的取值方式
這篇文章主要介紹了關(guān)于matplotlib及相關(guān)cmap參數(shù)的取值方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-11-11
在tensorflow下利用plt畫論文中l(wèi)oss,acc等曲線圖實(shí)例
這篇文章主要介紹了在tensorflow下利用plt畫論文中l(wèi)oss,acc等曲線圖實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-06-06
Conda與Python?venv虛擬環(huán)境的區(qū)別與使用方法詳解
隨著Python社區(qū)的成長,虛擬環(huán)境的概念和技術(shù)也在不斷發(fā)展,這篇文章主要介紹了Conda與Python?venv虛擬環(huán)境的區(qū)別與使用方法的相關(guān)資料,文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下2025-07-07
Python 平方列表中每個(gè)數(shù)字的多種操作
這篇文章主要介紹了Python 平方列表中每個(gè)數(shù)字的多種操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2021-03-03
Python利用代理ip實(shí)現(xiàn)自動(dòng)化爬蟲任務(wù)管理
本文主要介紹了Python利用代理ip實(shí)現(xiàn)自動(dòng)化爬蟲任務(wù)管理,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-06-06
使用Python設(shè)置Windows文件默認(rèn)打開程序
本文介紹了一個(gè)用于Windows系統(tǒng)設(shè)置文件默認(rèn)打開程序的Python工具,通過命令行和注冊表兩種方式修改關(guān)聯(lián),適用于Windows7/10/11,代碼包括設(shè)置默認(rèn)程序、兼容性處理和驗(yàn)證功能,并提供了使用示例,需要的朋友可以參考下2026-01-01
Python入門教程(十一)Python中的運(yùn)算符
這篇文章主要介紹了Python入門教程(十一)Python中的運(yùn)算符,Python是一門非常強(qiáng)大好用的語言,也有著易上手的特性,本文為入門教程,需要的朋友可以參考下2023-04-04
Python爬蟲實(shí)例——爬取美團(tuán)美食數(shù)據(jù)
這篇文章主要介紹了Python爬蟲如何爬取美團(tuán)美食數(shù)據(jù),文中講解非常詳細(xì),代碼幫助大家更好的理解和學(xué)習(xí),感興趣的朋友可以了解下2020-07-07

