Python操作JSON文件的知識(shí)點(diǎn)整理
json 模塊
Python 提供了內(nèi)置的 json 模塊來(lái)處理 JSON 格式的文件。
該模塊主要分為讀取和寫(xiě)入 JSON 文件。
讀取 JSON
使用 json.load() 或 json.loads() 方法來(lái)讀取 JSON 文件。
其中 json.load() 方法用于讀取文件中的 JSON 數(shù)據(jù),json.loads() 方法用于讀取字符串中的 JSON 數(shù)據(jù)。
寫(xiě)入 JSON
使用 json.dump() 或 json.dumps() 方法來(lái)寫(xiě)入 JSON 文件。
其中 json.dump() 方法用于寫(xiě)入 JSON 數(shù)據(jù)到文件中,json.dumps() 方法用于將 JSON 數(shù)據(jù)轉(zhuǎn)換為字符串。
基于上述內(nèi)容可以總結(jié)一下: json.load() , json.loads() , json.dump() 和 json.dumps() 中的 s 都是字符串 string 的縮寫(xiě)。
讀取與寫(xiě)入基本用法如下
提前準(zhǔn)備一個(gè) travel.json 文件,存放到 python 文件所在目錄。
import json
# 讀取json文件
with open('travel.json', 'r', encoding='utf-8') as f:
data = json.load(f)
# 寫(xiě)入json文件
with open('travel.new.json', 'w', encoding='utf-8') as f:
json.dump(data, f)
Tops:在使用 json.load() 和 json.loads() 讀取 json 文件時(shí),如果文件中存在格式錯(cuò)誤,會(huì)拋出 ValueError 異常。
json 模塊進(jìn)階用法
控制輸出格式
在處理 JSON 文件時(shí),還可以使用 json.dump() 方法的可選參數(shù)來(lái)控制輸出的格式,例如:
- sort_keys:按照鍵的字典序排序輸出。
- indent:縮進(jìn)輸出,可以指定縮進(jìn)的空格數(shù)。
import json
# # 讀取json文件
with open('travel.json', 'r', encoding='utf-8') as f:
data = json.load(f)
with open('travel.new.json', 'w', encoding='utf-8') as f:
json.dump(data, f, sort_keys=True, indent=4)
此時(shí)可以比對(duì)舊文件與新文件之間的差異,可以看到縮進(jìn)關(guān)系產(chǎn)生了變化。

在 JSON 中存儲(chǔ) Python 特殊類型
如果你要在 json 中存儲(chǔ) python 特殊類型,例如 datetime,需要使用 json.JSONEncoder 類和 json.JSONDecoder 類來(lái)處理。
import json
from datetime import datetime
# 日期編碼
class DateEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime):
return obj.strftime('%Y-%m-%d %H:%M:%S')
return json.JSONEncoder.default(self, obj)
d = {'date': datetime.now()}
json_str = json.dumps(d, cls=DateEncoder)
print(json_str)
# 日期解碼
class DateDecoder(json.JSONDecoder):
def __init__(self):
json.JSONDecoder.__init__(self, object_hook=self.dict_to_object)
def dict_to_object(self, d):
if 'date' in d:
d['date'] = datetime.strptime(d['date'], '%Y-%m-%d %H:%M:%S')
return d
data = json.loads(json_str, cls=DateDecoder)
print(data)
運(yùn)行代碼,可以得到編碼和解碼的輸出。
{"date": "2023-01-27 21:24:46"}
{'date': datetime.datetime(2023, 1, 27, 21, 24, 46)}
對(duì)數(shù)據(jù)進(jìn)行驗(yàn)證和清洗
JSON Schema 是一種用于驗(yàn)證 JSON 文檔的標(biāo)準(zhǔn),它可以用來(lái)確保 JSON 文檔符合預(yù)期的格式。
jsonschema 模塊需要提前安裝,示例代碼如下。
import json
import jsonschema
schema = {
"type": "object",
"properties": {
"name": {"type": "string"},
"age": {"type": "number"}
},
"required": ["name", "age"]
}
data = '{"name": "夢(mèng)想橡皮擦", "age": 28}'
try:
jsonschema.validate(json.loads(data), schema)
print("可用的JSON")
except jsonschema.exceptions.ValidationError as e:
print(e)
當(dāng)你的 json 格式正確時(shí),會(huì)輸出相應(yīng)的內(nèi)容,輸出錯(cuò)誤信息,測(cè)試代碼可以將 "required": ["name", "age"] 修改為 "required": ["name", "age" , "sex"]。
第三方模塊
在處理 JSON 格式文件時(shí)還可以使用第三方庫(kù)來(lái)更方便地操作,例如 pandas。
import pandas as pd
# 讀取json文件
data = pd.read_json('travel.json')
# 寫(xiě)入json文件
data.to_json('travel.pandas.json')
還有其他第三方庫(kù)也可以用來(lái)處理 JSON 格式文件,例如:
- ijson:迭代讀取大型 JSON 文件。
- jsonpickle:支持將 Python 對(duì)象序列化為 JSON 格式。
- jsonlines:簡(jiǎn)單而高效地讀取和寫(xiě)入文本文件中的 JSON 數(shù)據(jù)。
- simplejson:提供了一種比標(biāo)準(zhǔn)庫(kù)更快的 JSON 解析器和生成器。
- json-tricks:支持一些高級(jí)功能,例如壓縮和迭代。
到此這篇關(guān)于Python操作JSON文件的知識(shí)點(diǎn)整理的文章就介紹到這了,更多相關(guān)Python操作JSON內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python實(shí)現(xiàn)定時(shí)任務(wù)的八種方式總結(jié)
在日常工作中,我們常常會(huì)用到需要周期性執(zhí)行的任務(wù),下面這篇文章主要給大家介紹了關(guān)于python實(shí)現(xiàn)定時(shí)任務(wù)的八種方式,文中通過(guò)實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2023-01-01
python-jwt用戶認(rèn)證食用教學(xué)的實(shí)現(xiàn)方法
這篇文章主要介紹了python-jwt用戶認(rèn)證食用教學(xué)的實(shí)現(xiàn)方法,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-01-01
Sublime開(kāi)發(fā)python程序的示例代碼
本篇文章主要介紹了Sublime開(kāi)發(fā)python程序的示例代碼,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-01-01
python程序運(yùn)行添加命令行參數(shù)argparse模塊具體用法詳解
這篇文章主要給大家介紹了關(guān)于python程序運(yùn)行添加命令行參數(shù)argparse模塊具體用法的相關(guān)資料,argparse是Python內(nèi)置的一個(gè)用于命令項(xiàng)選項(xiàng)與參數(shù)解析的模塊,通過(guò)在程序中定義好我們需要的參數(shù),需要的朋友可以參考下2024-01-01

