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

在默認(rèn)情況下,pip會(huì)訪問https://pypi.org/simple/來獲得三方庫相關(guān)的數(shù)據(jù),但是國內(nèi)訪問這個(gè)網(wǎng)站的速度并不是十分理想,因此國內(nèi)用戶可以使用豆瓣網(wǎng)提供的鏡像來替代這個(gè)默認(rèn)的下載源,操作如下所示。
可以通過pip search命令根據(jù)名字查找需要的三方庫,可以通過pip list命令來查看已經(jīng)安裝過的三方庫。如果想更新某個(gè)三方庫,可以使用pip install -U或pip install --upgrade;如果要?jiǎng)h除某個(gè)三方庫,可以使用pip uninstall命令。
1、搜索ujson三方庫
pip search ujson pip index versions ujson (Python 3.10+查看可用的版本)
2、查看已經(jīng)安裝的三方庫
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。
到此這篇關(guān)于Python進(jìn)行JSON數(shù)據(jù)處理的全攻略的文章就介紹到這了,更多相關(guān)Python JSON數(shù)據(jù)處理內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
一文帶你玩轉(zhuǎn)Python必備的幾種數(shù)據(jù)格式
在Python開發(fā)中,數(shù)據(jù)格式的選擇直接影響著程序的性能和可維護(hù)性,本文將詳細(xì)介紹Python開發(fā)中最常用的幾種數(shù)據(jù)格式,希望可以幫助大家選擇最合適的數(shù)據(jù)表示方式2025-06-06
使用Python解決常見格式圖像讀取nii,dicom,mhd
這篇文章主要介紹了使用Python解決常見格式圖像讀取nii,dicom,mhd,下文具體操作過程需要的小伙伴可以參考一下2022-04-04
關(guān)于python實(shí)現(xiàn)常用的相似度計(jì)算方法
這篇文章主要介紹了關(guān)于python實(shí)現(xiàn)常用的相似度計(jì)算方法,最初的相似度計(jì)算是為了表征向量的重合程度的,在這里最經(jīng)典的就是余弦相似度了,當(dāng)然使用正弦或者是正切等等三角函數(shù)也都是可以的,需要的朋友可以參考下2023-07-07
windows下安裝Python虛擬環(huán)境virtualenvwrapper-win
這篇文章主要介紹了windows下安裝Python虛擬環(huán)境virtualenvwrapper-win,內(nèi)容超簡單,非常不錯(cuò),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2019-06-06
Python下使用Trackbar實(shí)現(xiàn)繪圖板
這篇文章主要為大家詳細(xì)介紹了Python下使用Trackbar實(shí)現(xiàn)繪圖板,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-10-10
tensorflow轉(zhuǎn)onnx的實(shí)現(xiàn)方法
本文主要介紹了tensorflow轉(zhuǎn)onnx的實(shí)現(xiàn)方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-03-03

