欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python使用json模塊讀取和寫入JSON數(shù)據(jù)

 更新時間:2025年03月06日 09:48:18   作者:莫比烏斯之夢  
Python 提供了內(nèi)置的 json 模塊,使得我們可以方便地解析 JSON 數(shù)據(jù)(讀?。┖蜕?nbsp;JSON 數(shù)據(jù)(寫入),下面小編就來為大家介紹一下具體的操作步驟吧

在現(xiàn)代軟件開發(fā)中,JSON(JavaScript Object Notation) 已成為最流行的數(shù)據(jù)交換格式之一。Python 提供了內(nèi)置的 json 模塊,使得我們可以方便地解析 JSON 數(shù)據(jù)(讀?。┖蜕?JSON 數(shù)據(jù)(寫入)。無論是 Web API 交互、配置文件存儲,還是數(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 類型示例
dictobject{"name": "Alice", "age": 25}
list / tuplearray["apple", "banana", "cherry"]
strstring"hello"
int / floatnumber42, 3.14
booltrue / falsetrue, false
Nonenullnull

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 對象。

2.2 從 JSON 文件讀取

假設(shè)有一個 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 文件對象。
  • 輸出:Python dict 對象。

3. 寫入 JSON 數(shù)據(jù)

Python 可以將數(shù)據(jù)寫入字符串或文件。

3.1 將 Python 對象轉(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 對象寫入 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(或其他可序列化對象)。
  • 輸出:寫入 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 編碼與解碼(對象序列化)

如果 JSON 數(shù)據(jù)包含自定義對象,默認(rèn) json.dumps() 無法處理:

import json
from datetime import datetime

data = {"name": "Alice", "time": datetime.now()}

# 會報錯:Object of type datetime is not JSON serializable
json_str = json.dumps(data)

可以使用 default 參數(shù),將 datetime 對象轉(zhuǎn)換為字符串:

def json_serial(obj):
    if isinstance(obj, datetime):
        return obj.isoformat()  # 轉(zhuǎn)換為 ISO 8601 時間格式
    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 解析錯誤

解析 JSON 時,可能會遇到格式錯誤:

import json

invalid_json = '{"name": "Tom", "age": 30,}'  # 末尾多了逗號

try:
    data = json.loads(invalid_json)
except json.JSONDecodeError as e:
    print(f"JSON 解析錯誤: {e}")

輸出:

JSON 解析錯誤: Expecting property name enclosed in double quotes

7. JSON 讀寫的最佳實(shí)踐

讀取 JSON 時使用 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"錯誤: {e}")

寫入 JSON 時使用 indent=4 讓數(shù)據(jù)更易讀

json.dump(data, file, indent=4)

處理非標(biāo)準(zhǔn)數(shù)據(jù)類型時,使用 default 進(jìn)行序列化

json.dumps(data, default=json_serial)

8. 結(jié)論

操作方法
從字符串讀取 JSONjson.loads(json_str)
從文件讀取 JSONjson.load(file)
將 Python 對象轉(zhuǎn)換為 JSON 字符串json.dumps(obj)
將 Python 對象寫入 JSON 文件json.dump(obj, file)
格式化 JSON(縮進(jìn))json.dumps(obj, indent=4)
解析錯誤處理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ù)的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評論