Python進行JSON數(shù)據(jù)處理的全攻略
JSON概述
在Python中,我們可以將程序中的數(shù)據(jù)以JSON格式進行保存。JSON是“JavaScript Object Notation”的縮寫,它本來是JavaScript語言中創(chuàng)建對象的一種字面量語法,現(xiàn)在已經被廣泛的應用于跨語言跨平臺的數(shù)據(jù)交換。使用JSON的原因非常簡單,因為它結構緊湊而且是純文本,任何操作系統(tǒng)和編程語言都能處理純文本,這就是實現(xiàn)跨語言跨平臺數(shù)據(jù)交換的前提條件。目前JSON基本上已經取代了XML(可擴展標記語言)作為異構系統(tǒng)間交換數(shù)據(jù)的事實標準??梢栽?a rel="external nofollow" target="_blank">JSON的官方網站找到更多關于JSON的知識,這個網站還提供了每種語言處理JSON數(shù)據(jù)格式可以使用的工具或三方庫。
在JSON中使用的數(shù)據(jù)類型(JavaScript數(shù)據(jù)類型)和Python中的數(shù)據(jù)類型也是很容易找到對應關系的,大家可以看看下面的兩張表。
表1:JavaScript數(shù)據(jù)類型(值)對應的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ù)類型(值)對應的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模塊有四個比較重要的函數(shù),分別是:
dump- 將Python對象按照JSON格式序列化到文件中dumps- 將Python對象處理成JSON格式的字符串load- 將文件中的JSON數(shù)據(jù)反序列化成對象loads- 將字符串的內容反序列化成Python對象
1. 基本JSON操作
import json
# Python字典數(shù)據(jù)
data = {
"name": "張三",
"age": 30,
"is_student": False,
"courses": ["數(shù)學", "英語", "計算機"],
"address": {
"street": "人民路123號",
"city": "北京"
}
}
# 將Python對象轉換為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、復雜數(shù)據(jù)類型處理
import json
from datetime import datetime
# 包含復雜數(shù)據(jù)類型的Python對象
complex_data = {
"timestamp": datetime.now(),
"set_data": {1, 2, 3},
"custom_object": type('CustomClass', (), {'attr': 'value'})
}
# 自定義JSON編碼器處理復雜類型
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)
# 序列化復雜對象
json_string = json.dumps(complex_data, cls=ComplexEncoder, indent=2)
print("復雜對象JSON:")
print(json_string)3. JSON配置文件管理
import json
import os
# 配置文件路徑
CONFIG_FILE = 'config.json'
# 默認配置
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)建默認配置文件")
# 讀取配置文件
with open(CONFIG_FILE, 'r', encoding='utf-8') as f:
config = json.load(f)
print("當前配置:")
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響應
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ù)時出錯: {e}")5. JSON數(shù)據(jù)驗證
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"]
}
# 驗證JSON數(shù)據(jù)
try:
validate(instance=user_data, schema=schema)
print("JSON數(shù)據(jù)驗證通過")
except ValidationError as e:
print(f"驗證錯誤: {e}")6.包管理工具pip
Python標準庫中的json模塊在數(shù)據(jù)序列化和反序列化時性能并不是非常理想,為了解決這個問題,可以使用三方庫ujson來替換json。所謂三方庫,是指非公司內部開發(fā)和使用的,也不是來自于官方標準庫的Python模塊,這些模塊通常由其他公司、組織或個人開發(fā),所以被稱為三方庫。雖然Python語言的標準庫雖然已經提供了諸多模塊來方便我們的開發(fā),但是對于一個強大的語言來說,它的生態(tài)圈一定也是非常繁榮的。
之前安裝Python解釋器時,默認情況下已經勾選了安裝pip,大家可以在命令提示符或終端中通過pip --version來確定是否已經擁有了pip。pip是Python的包管理工具,通過pip可以查找、安裝、卸載、更新Python的三方庫或工具,macOS和Linux系統(tǒng)應該使用pip3。例如要安裝替代json模塊的ujson,可以使用下面的命令。
pip install ujson

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

3、更新ujson三方庫
pip install -U ujson
4、刪除ujson三方庫
pip uninstall -y ujson
提示:如果要更新pip自身,對于macOS系統(tǒng)來說,可以使用命令pip install -U pip。在Windows系統(tǒng)上,可以將命令替換為python -m pip install -U --user pip。
到此這篇關于Python進行JSON數(shù)據(jù)處理的全攻略的文章就介紹到這了,更多相關Python JSON數(shù)據(jù)處理內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
一文帶你玩轉Python必備的幾種數(shù)據(jù)格式
在Python開發(fā)中,數(shù)據(jù)格式的選擇直接影響著程序的性能和可維護性,本文將詳細介紹Python開發(fā)中最常用的幾種數(shù)據(jù)格式,希望可以幫助大家選擇最合適的數(shù)據(jù)表示方式2025-06-06
使用Python解決常見格式圖像讀取nii,dicom,mhd
這篇文章主要介紹了使用Python解決常見格式圖像讀取nii,dicom,mhd,下文具體操作過程需要的小伙伴可以參考一下2022-04-04
windows下安裝Python虛擬環(huán)境virtualenvwrapper-win
這篇文章主要介紹了windows下安裝Python虛擬環(huán)境virtualenvwrapper-win,內容超簡單,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下2019-06-06

