自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

Python處理Json數(shù)據(jù)格式的常見的20種小技巧

開發(fā) 前端
20 種處理 JSON 數(shù)據(jù)的常見小技巧,涵蓋了從基本的序列化和反序列化到高級的自定義編碼和解碼。通過這些技巧,你可以更高效、更靈活地處理 JSON 數(shù)據(jù)。

處理 JSON 數(shù)據(jù)是 Python 編程中非常常見的任務(wù)。Python 提供了 json 模塊來方便地處理 JSON 數(shù)據(jù)。以下是 20 種處理 JSON 數(shù)據(jù)的常見小技巧,幫助你更高效地完成任務(wù)。

1. 導(dǎo)入 json 模塊

首先,確保導(dǎo)入 json 模塊。

import json

2. 將 Python 對象轉(zhuǎn)換為 JSON 字符串

使用 json.dumps() 方法將 Python 對象轉(zhuǎn)換為 JSON 字符串。

data = {
    "name": "Alice",
    "age": 30,
    "is_student": False
}
json_str = json.dumps(data)
print(json_str)  # 輸出: {"name": "Alice", "age": 30, "is_student": false}

3. 將 JSON 字符串轉(zhuǎn)換為 Python 對象

使用 json.loads() 方法將 JSON 字符串轉(zhuǎn)換為 Python 對象。

json_str = '{"name": "Alice", "age": 30, "is_student": false}'
data = json.loads(json_str)
print(data)  # 輸出: {'name': 'Alice', 'age': 30, 'is_student': False}

4. 讀取 JSON 文件

使用 json.load() 方法從文件中讀取 JSON 數(shù)據(jù)。

with open('data.json', 'r') as file:
    data = json.load(file)
print(data)

5. 寫入 JSON 文件

使用 json.dump() 方法將 Python 對象寫入 JSON 文件。

data = {
    "name": "Alice",
    "age": 30,
    "is_student": False
}
with open('data.json', 'w') as file:
    json.dump(data, file)

6. 格式化 JSON 輸出

使用 indent 參數(shù)格式化 JSON 輸出,使其更易讀。

data = {
    "name": "Alice",
    "age": 30,
    "is_student": False
}
json_str = json.dumps(data, indent=4)
print(json_str)
# 輸出:
# {
#     "name": "Alice",
#     "age": 30,
#     "is_student": false
# }

7. 處理日期和時間

使用 json 模塊的 default 參數(shù)處理日期和時間對象。

from datetime import datetime
def json_default(value):
    if isinstance(value, datetime):
        return value.isoformat()
    raise TypeError(f"Type {type(value)} not serializable")
data = {
    "name": "Alice",
    "timestamp": datetime.now()
}
json_str = json.dumps(data, default=json_default)
print(json_str)

8. 自定義解碼器

使用 object_hook 參數(shù)自定義解碼器。

def custom_decoder(obj):
    if 'timestamp' in obj:
        obj['timestamp'] = datetime.fromisoformat(obj['timestamp'])
    return obj
json_str = '{"name": "Alice", "timestamp": "2023-10-01T12:00:00"}'
data = json.loads(json_str, object_hook=custom_decoder)
print(data)  # 輸出: {'name': 'Alice', 'timestamp': datetime.datetime(2023, 10, 1, 12, 0)}

9. 處理 Unicode

使用 ensure_ascii 參數(shù)處理 Unicode 字符。

data = {
    "name": "Alice",
    "message": "你好,世界!"
}
json_str = json.dumps(data, ensure_ascii=False)
print(json_str)  # 輸出: {"name": "Alice", "message": "你好,世界!"}

10. 處理特殊字符

使用 separators 參數(shù)處理特殊字符。

data = {
    "name": "Alice",
    "age": 30
}
json_str = json.dumps(data, separators=(',', ':'))
print(json_str)  # 輸出: {"name":"Alice","age":30}

11. 處理嵌套數(shù)據(jù)

處理嵌套的 JSON 數(shù)據(jù)。

data = {
    "name": "Alice",
    "details": {
        "age": 30,
        "is_student": False
    }
}
json_str = json.dumps(data)
print(json_str)  # 輸出: {"name": "Alice", "details": {"age": 30, "is_student": false}}

12. 處理列表

處理 JSON 列表。

data = [
    {"name": "Alice", "age": 30},
    {"name": "Bob", "age": 25}
]
json_str = json.dumps(data)
print(json_str)  # 輸出: [{"name": "Alice", "age": 30}, {"name": "Bob", "age": 25}]

13. 處理空值

處理 JSON 中的 null 值。

data = {
    "name": "Alice",
    "age": None
}
json_str = json.dumps(data)
print(json_str)  # 輸出: {"name": "Alice", "age": null}

14. 處理布爾值

處理 JSON 中的布爾值。

data = {
    "name": "Alice",
    "is_student": True
}
json_str = json.dumps(data)
print(json_str)  # 輸出: {"name": "Alice", "is_student": true}

15. 處理數(shù)字

處理 JSON 中的數(shù)字。

data = {
    "name": "Alice",
    "age": 30,
    "height": 1.65
}
json_str = json.dumps(data)
print(json_str)  # 輸出: {"name": "Alice", "age": 30, "height": 1.65}

16. 處理字符串

處理 JSON 中的字符串。

data = {
    "name": "Alice",
    "message": "Hello, World!"
}
json_str = json.dumps(data)
print(json_str)  # 輸出: {"name": "Alice", "message": "Hello, World!"}

17. 處理特殊字符

處理 JSON 中的特殊字符。

data = {
    "name": "Alice",
    "message": "This is a \"quoted\" message."
}
json_str = json.dumps(data)
print(json_str)  # 輸出: {"name": "Alice", "message": "This is a \"quoted\" message."}

18. 處理異常

處理 JSON 解析異常。

json_str = '{"name": "Alice", "age": 30, "is_student": false}'
try:
    data = json.loads(json_str)
    print(data)
except json.JSONDecodeError as e:
    print(f"JSON 解析錯誤: {e}")

19. 處理大文件

處理大文件時,使用流式處理。

import json
def read_large_json_file(file_path):
    with open(file_path, 'r') as file:
        for line in file:
            data = json.loads(line)
            yield data
for item in read_large_json_file('large_data.json'):
    print(item)

20. 處理 JSON 數(shù)組

處理 JSON 數(shù)組中的數(shù)據(jù)。

json_str = '[{"name": "Alice", "age": 30}, {"name": "Bob", "age": 25}]'
data = json.loads(json_str)
for item in data:
    print(item)
# 輸出:
# {'name': 'Alice', 'age': 30}
# {'name': 'Bob', 'age': 25}

總結(jié)

以上是 20 種處理 JSON 數(shù)據(jù)的常見小技巧,涵蓋了從基本的序列化和反序列化到高級的自定義編碼和解碼。通過這些技巧,你可以更高效、更靈活地處理 JSON 數(shù)據(jù)。

責(zé)任編輯:武曉燕 來源: 測試開發(fā)學(xué)習(xí)交流
相關(guān)推薦

2019-07-22 08:49:37

PythonJSON編程語言

2024-04-15 13:13:04

PythonJSON

2010-01-06 14:04:55

Json數(shù)據(jù)格式

2014-08-12 10:15:42

數(shù)據(jù)格式JSONXML

2009-09-07 19:02:07

JSON是什么

2020-09-28 10:58:26

Google AI技術(shù)

2010-01-06 13:23:20

JSON數(shù)據(jù)格式

2013-03-27 10:51:44

iOSjson解析網(wǎng)絡(luò)交互數(shù)據(jù)格式解析

2011-04-11 09:48:59

AjaxWEB服務(wù)

2009-04-13 11:20:46

IBMdWWeb

2010-02-06 14:32:45

ibmdw

2024-12-19 00:12:02

APIJSON數(shù)據(jù)

2009-03-09 09:34:56

AjaxHTMLJavaScript

2017-01-05 09:48:51

大數(shù)據(jù)數(shù)據(jù)格式生態(tài)

2016-12-20 16:40:13

CarbonData數(shù)據(jù)存儲大數(shù)據(jù)

2018-09-18 11:16:11

MapReduceXML大數(shù)據(jù)

2017-03-27 14:58:03

MapReduce數(shù)據(jù)類型數(shù)據(jù)格式

2019-11-20 12:03:42

Python數(shù)據(jù)爬蟲

2016-11-10 13:00:32

網(wǎng)絡(luò)傳輸協(xié)議pythonhttp

2019-07-04 19:06:04

技術(shù)人工智能大數(shù)據(jù)
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號