Python進(jìn)行JSON數(shù)據(jù)處理的全攻略
JSON概述
在Python中,我們可以將程序中的數(shù)據(jù)以JSON格式進(jìn)行保存。JSON是“JavaScript Object Notation”的縮寫,它本來(lái)是JavaScript語(yǔ)言中創(chuàng)建對(duì)象的一種字面量語(yǔ)法,現(xiàn)在已經(jīng)被廣泛的應(yīng)用于跨語(yǔ)言跨平臺(tái)的數(shù)據(jù)交換。使用JSON的原因非常簡(jiǎn)單,因?yàn)樗Y(jié)構(gòu)緊湊而且是純文本,任何操作系統(tǒng)和編程語(yǔ)言都能處理純文本,這就是實(shí)現(xiàn)跨語(yǔ)言跨平臺(tái)數(shù)據(jù)交換的前提條件。目前JSON基本上已經(jīng)取代了XML(可擴(kuò)展標(biāo)記語(yǔ)言)作為異構(gòu)系統(tǒng)間交換數(shù)據(jù)的事實(shí)標(biāo)準(zhǔn)。可以在JSON的官方網(wǎng)站找到更多關(guān)于JSON的知識(shí),這個(gè)網(wǎng)站還提供了每種語(yǔ)言處理JSON數(shù)據(jù)格式可以使用的工具或三方庫(kù)。
在JSON中使用的數(shù)據(jù)類型(JavaScript數(shù)據(jù)類型)和Python中的數(shù)據(jù)類型也是很容易找到對(duì)應(yīng)關(guān)系的,大家可以看看下面的兩張表。
表1:JavaScript數(shù)據(jù)類型(值)對(duì)應(yīng)的Python數(shù)據(jù)類型(值)
| JSON | Python |
| object | dict |
| array | list |
| string | str |
| number | int / float |
| number(real) | float |
| boolean(true/ false) | bool (True/ False) |
| null | None |
表2:Python數(shù)據(jù)類型(值)對(duì)應(yīng)的JavaScript數(shù)據(jù)類型(值)
| Python | JSON |
| dict | object |
| list/ tuple | array |
| str | string |
| int/ float | number |
| bool(True/ False) | boolean(true / false) |
| None | null |
python 中json模塊有四個(gè)比較重要的函數(shù),分別是:
dump- 將Python對(duì)象按照J(rèn)SON格式序列化到文件中dumps- 將Python對(duì)象處理成JSON格式的字符串load- 將文件中的JSON數(shù)據(jù)反序列化成對(duì)象loads- 將字符串的內(nèi)容反序列化成Python對(duì)象
1. 基本JSON操作
import json
# Python字典數(shù)據(jù)
data = {
"name": "張三",
"age": 30,
"is_student": False,
"courses": ["數(shù)學(xué)", "英語(yǔ)", "計(jì)算機(jī)"],
"address": {
"street": "人民路123號(hào)",
"city": "北京"
}
}
# 將Python對(duì)象轉(zhuǎn)換為JSON字符串
json_string = json.dumps(data, indent=4, ensure_ascii=False)
print("JSON字符串:")
print(json_string)
# 將JSON字符串保存到文件
with open('data.json', 'w', encoding='utf-8') as f:
json.dump(data, f, indent=4, ensure_ascii=False)
# 從文件讀取JSON數(shù)據(jù)
with open('data.json', 'r', encoding='utf-8') as f:
loaded_data = json.load(f)
print("\n從文件加載的數(shù)據(jù):")
print(loaded_data)2、復(fù)雜數(shù)據(jù)類型處理
import json
from datetime import datetime
# 包含復(fù)雜數(shù)據(jù)類型的Python對(duì)象
complex_data = {
"timestamp": datetime.now(),
"set_data": {1, 2, 3},
"custom_object": type('CustomClass', (), {'attr': 'value'})
}
# 自定義JSON編碼器處理復(fù)雜類型
class ComplexEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime):
return obj.isoformat()
elif isinstance(obj, set):
return list(obj)
elif hasattr(obj, '__dict__'):
return obj.__dict__
return super().default(obj)
# 序列化復(fù)雜對(duì)象
json_string = json.dumps(complex_data, cls=ComplexEncoder, indent=2)
print("復(fù)雜對(duì)象JSON:")
print(json_string)3. JSON配置文件管理
import json
import os
# 配置文件路徑
CONFIG_FILE = 'config.json'
# 默認(rèn)配置
default_config = {
"app_name": "MyApp",
"version": "1.0",
"settings": {
"theme": "dark",
"language": "zh-CN",
"auto_update": True
}
}
# 檢查并創(chuàng)建配置文件
if not os.path.exists(CONFIG_FILE):
with open(CONFIG_FILE, 'w', encoding='utf-8') as f:
json.dump(default_config, f, indent=4)
print("已創(chuàng)建默認(rèn)配置文件")
# 讀取配置文件
with open(CONFIG_FILE, 'r', encoding='utf-8') as f:
config = json.load(f)
print("當(dāng)前配置:")
print(json.dumps(config, indent=4, ensure_ascii=False))
# 修改并保存配置
config['settings']['theme'] = 'light'
config['version'] = '1.1'
with open(CONFIG_FILE, 'w', encoding='utf-8') as f:
json.dump(config, f, indent=4)
print("\n配置已更新")4. 處理JSON API響應(yīng)
import json
import urllib.request
from pprint import pprint
# 從API獲取JSON數(shù)據(jù)
def fetch_json_data(url):
with urllib.request.urlopen(url) as response:
data = json.loads(response.read().decode('utf-8'))
return data
# 示例API (JSONPlaceholder)
api_url = "https://jsonplaceholder.typicode.com/users/1"
try:
user_data = fetch_json_data(api_url)
print("從API獲取的用戶數(shù)據(jù):")
pprint(user_data)
# 保存到本地
with open('user_data.json', 'w', encoding='utf-8') as f:
json.dump(user_data, f, indent=2, ensure_ascii=False)
print("\n數(shù)據(jù)已保存到 user_data.json")
except Exception as e:
print(f"獲取數(shù)據(jù)時(shí)出錯(cuò): {e}")5. JSON數(shù)據(jù)驗(yàn)證
import json
from jsonschema import validate, ValidationError
# JSON數(shù)據(jù)
user_data = {
"id": 1,
"name": "John Doe",
"email": "john@example.com",
"age": 30
}
# JSON Schema定義
schema = {
"type": "object",
"properties": {
"id": {"type": "number"},
"name": {"type": "string"},
"email": {"type": "string", "format": "email"},
"age": {"type": "number", "minimum": 18}
},
"required": ["id", "name", "email"]
}
# 驗(yàn)證JSON數(shù)據(jù)
try:
validate(instance=user_data, schema=schema)
print("JSON數(shù)據(jù)驗(yàn)證通過(guò)")
except ValidationError as e:
print(f"驗(yàn)證錯(cuò)誤: {e}")6.包管理工具pip
Python標(biāo)準(zhǔn)庫(kù)中的json模塊在數(shù)據(jù)序列化和反序列化時(shí)性能并不是非常理想,為了解決這個(gè)問(wèn)題,可以使用三方庫(kù)ujson來(lái)替換json。所謂三方庫(kù),是指非公司內(nèi)部開(kāi)發(fā)和使用的,也不是來(lái)自于官方標(biāo)準(zhǔn)庫(kù)的Python模塊,這些模塊通常由其他公司、組織或個(gè)人開(kāi)發(fā),所以被稱為三方庫(kù)。雖然Python語(yǔ)言的標(biāo)準(zhǔn)庫(kù)雖然已經(jīng)提供了諸多模塊來(lái)方便我們的開(kāi)發(fā),但是對(duì)于一個(gè)強(qiáng)大的語(yǔ)言來(lái)說(shuō),它的生態(tài)圈一定也是非常繁榮的。
之前安裝Python解釋器時(shí),默認(rèn)情況下已經(jīng)勾選了安裝pip,大家可以在命令提示符或終端中通過(guò)pip --version來(lái)確定是否已經(jīng)擁有了pip。pip是Python的包管理工具,通過(guò)pip可以查找、安裝、卸載、更新Python的三方庫(kù)或工具,macOS和Linux系統(tǒng)應(yīng)該使用pip3。例如要安裝替代json模塊的ujson,可以使用下面的命令。
pip install ujson

在默認(rèn)情況下,pip會(huì)訪問(wèn)https://pypi.org/simple/來(lái)獲得三方庫(kù)相關(guān)的數(shù)據(jù),但是國(guó)內(nèi)訪問(wèn)這個(gè)網(wǎng)站的速度并不是十分理想,因此國(guó)內(nèi)用戶可以使用豆瓣網(wǎng)提供的鏡像來(lái)替代這個(gè)默認(rèn)的下載源,操作如下所示。
可以通過(guò)pip search命令根據(jù)名字查找需要的三方庫(kù),可以通過(guò)pip list命令來(lái)查看已經(jīng)安裝過(guò)的三方庫(kù)。如果想更新某個(gè)三方庫(kù),可以使用pip install -U或pip install --upgrade;如果要?jiǎng)h除某個(gè)三方庫(kù),可以使用pip uninstall命令。
1、搜索ujson三方庫(kù)
pip search ujson pip index versions ujson (Python 3.10+查看可用的版本)
2、查看已經(jīng)安裝的三方庫(kù)
pip list

3、更新ujson三方庫(kù)
pip install -U ujson
4、刪除ujson三方庫(kù)
pip uninstall -y ujson
提示:如果要更新pip自身,對(duì)于macOS系統(tǒng)來(lái)說(shuō),可以使用命令pip install -U pip。在Windows系統(tǒng)上,可以將命令替換為python -m pip install -U --user pip。
到此這篇關(guān)于Python進(jìn)行JSON數(shù)據(jù)處理的全攻略的文章就介紹到這了,更多相關(guān)Python JSON數(shù)據(jù)處理內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
pycharm出現(xiàn)No?pyvenv.cfg?file錯(cuò)誤的問(wèn)題解決
本文主要介紹了pycharm出現(xiàn)No?pyvenv.cfg?file錯(cuò)誤的問(wèn)題解決,主要是通過(guò)恢復(fù)歷史記錄中的未刪除狀態(tài)來(lái)解決,下面就來(lái)詳細(xì)的介紹一下,感興趣的可以了解一下2025-05-05
python基于OpenCV模塊實(shí)現(xiàn)視頻流數(shù)據(jù)切割為圖像幀數(shù)據(jù)(流程分析)
這篇文章主要介紹了python基于OpenCV模塊實(shí)現(xiàn)視頻流數(shù)據(jù)切割為圖像幀數(shù)據(jù),這里今天主要是實(shí)踐一下視頻流數(shù)據(jù)的預(yù)處理工作,需要的朋友可以參考下2022-05-05
從基礎(chǔ)到進(jìn)階詳解Python中字符串分割的常見(jiàn)方法
字符串分割是編程中常見(jiàn)的操作,本文全面介紹了Python中的字符串分割方法,涵蓋基礎(chǔ)操作和高級(jí)技巧,希望可以幫助大家掌握Python字符串分割的技巧2026-04-04
python 通過(guò)logging寫入日志到文件和控制臺(tái)的實(shí)例
下面小編就為大家分享一篇python 通過(guò)logging寫入日志到文件和控制臺(tái)的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-04-04

