Python內(nèi)置json實(shí)現(xiàn)數(shù)據(jù)本地持久化詳解
四個(gè)json函數(shù)
| 函數(shù) | |
|---|---|
| json.load() | 將本地json數(shù)據(jù)文件讀取出來,并以列表形式返回從文件對象中讀取 JSON 格式的字符串,并將其反序列化為 Python 對象 |
| json.loads() | 將 JSON 格式的字符串反序列化為 Python 對象 |
| json.dump() | 將 Python 對象序列化為 JSON 格式的字符串,并將其寫入文件對象。 |
| json.dumps() | 將 Python 對象序列化為 JSON 格式的字符串 |
將數(shù)據(jù)以json文件保存在本地的方式
使用file.open()
實(shí)例數(shù)據(jù)
class Person:
name = None
age = None
def __init__(self, name, age):
self.name = name
self.age = age
person1 = Person("Alice", 30)
person2 = Person("Bob", 25)
person3 = Person("Charlie", 35)
person4 = Person("David", 28)
person5 = Person("Eve", 32)
persons = [person1, person2, person3, person4, person5]
person_list = [person.__dict__ for person in persons]
print(person_list)
'''
[{'name': 'Alice', 'age': 30}, {'name': 'Bob', 'age': 25}, {'name': 'Charlie', 'age': 35}, {'name': 'David', 'age': 28}, {'name': 'Eve', 'age': 32}]
<class 'list'>
返回的是一個(gè)列表
'''
object.__dict__
object.__dict__ 是 Python 中的一個(gè)特殊屬性,用于存儲對象的實(shí)例屬性。每個(gè) Python 對象都有一個(gè) __dict__ 屬性,它是一個(gè)字典,包含了對象的所有實(shí)例屬性及其對應(yīng)的值
將對象的數(shù)據(jù)保存到j(luò)son中,需要先使用對象.__dict__將每一個(gè)對象的字典形式取出(使用列表推導(dǎo)式),在將每一個(gè)對象的字典形式保存在列表中,將列表保存在json文件中
data_list = [person.__dict__ for person in persons] # 列表推導(dǎo)式
保存數(shù)據(jù)
def load_data():
with open(data_file, 'r', encoding='utf-8') as file:
return json.load(file)
讀取數(shù)據(jù)
def save_data(persons):
with open(data_file, 'w', encoding='utf-8') as file:
json.dump([person.__dict__ for person in persons], file, indent=2)
注意事項(xiàng)
open() 函數(shù)自動創(chuàng)建文件:
'r' 模式(只讀模式)下,如果文件不存在,會直接拋出 FileNotFoundError,不會自動創(chuàng)建文件。
只有使用'w'(寫入模式)或 'a'(追加模式)時(shí),如果文件不存在,才會自動創(chuàng)建。
實(shí)際案例:
class HouseService:
house_list = []
data_file = os.path.join(os.path.dirname(__file__), 'house_data.json')
def __init__(self):
self.load_data()
if not self.house_list:
house1 = House('1', 'lihua', '123456', '鄭州中原區(qū)', 800, '未出租')
house2 = House('2', 'jack', '123452', '鄭州市二七區(qū)', 900, '未出租')
self.house_list.append(house1)
self.house_list.append(house2)
self.save_data()
# 加載房屋數(shù)據(jù)
def load_data(self):
try:
with open(self.data_file, 'r', encoding='utf-8') as file:
data = json.load(file)
self.house_list = [House(**house) for house in data]
except FileNotFoundError:
self.house_list = []
# 保存房屋數(shù)據(jù)
def save_data(self):
with open(self.data_file, 'w', encoding='utf-8') as file:
json.dump([house.__dict__ for house in self.house_list], file, ensure_ascii=False, indent=4)
在此案例下,load_data()函數(shù)如果不采用異常捕獲的話,且文件夾中并沒有house_data.json文件時(shí),系統(tǒng)將直接拋出異常,當(dāng)捕獲異常之后,并初始化數(shù)據(jù)列表,程序可以繼續(xù)向下進(jìn)行,來到save_data()保存數(shù)據(jù),并自動創(chuàng)建json文件
所以在開發(fā)過程中,編寫保存房屋數(shù)據(jù)時(shí),注意異常捕獲
追加數(shù)據(jù)
如果有新的數(shù)據(jù)需要保存,不能直接使用mode='a', 'a'模式追加寫入,會導(dǎo)致JSON文件變成多個(gè)獨(dú)立對象而不是有效數(shù)組,新追加的數(shù)據(jù)會直接保存在[]外面
[{...}, {...}] // 原始數(shù)據(jù)
{...} // 新追加數(shù)據(jù)(格式錯(cuò)誤)
所以要向json文件中追加數(shù)據(jù),需要用到一下方法:
采用讀取→修改→覆蓋寫入的模式(而不是直接追加)
使用'w'模式保證每次寫入完整的JSON數(shù)組結(jié)構(gòu)
import os
import json
# 示例數(shù)據(jù)
data = {
"name": "Alice",
"age": 30,
"skills": ["Python", "Docker"],
"is_active": True
}
data_dile = os.path.join(os.path.dirname(__file__), 'person_data.json')
def save_data(data):
with open(data_dile, 'w', encoding='utf-8') as file:
json.dump(data, file, indent=2)
def load_data():
with open(data_dile, 'r', encoding='utf-8') as file:
data = json.load(file)
return data
exist_data = load_data() # 取出現(xiàn)有數(shù)據(jù)
print(type(exist_data)) # <class 'list'>
exist_data.append(data) # 想列表中追加數(shù)據(jù)
save_data(exist_data) # 保存追加過數(shù)據(jù)后的列表到此這篇關(guān)于Python內(nèi)置json實(shí)現(xiàn)數(shù)據(jù)本地持久化詳解的文章就介紹到這了,更多相關(guān)Python數(shù)據(jù)本地持久化內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
幫你快速上手Jenkins并實(shí)現(xiàn)自動化部署
在未學(xué)習(xí)Jenkins之前,只是對Jenkins有一個(gè)比較模糊的理解,即Jenkins是一個(gè)自動化構(gòu)建項(xiàng)目發(fā)布的工具,可以實(shí)現(xiàn)代碼->github或者gitlab庫->jenkins自動部署->訪問的整體的過程,而無需人為重新打包,今天就帶大家詳細(xì)了解一下,幫你快速上手Jenkins,需要的朋友可以參考下2021-06-06
python使用Akshare與Streamlit實(shí)現(xiàn)股票估值分析教程(圖文代碼)
入職測試中的一道題,要求:從Akshare下載某一個(gè)股票近十年的財(cái)務(wù)報(bào)表包括,資產(chǎn)負(fù)債表,利潤表,現(xiàn)金流量表,保存到本地Csv文件,對該公司進(jìn)行財(cái)務(wù)分析,如提取近五年,營業(yè)收入,凈利潤數(shù)據(jù),并且算出同比增長,通過Pandas處理、Matplotlib可視化及Streamlit部署,實(shí)現(xiàn)財(cái)務(wù)數(shù)據(jù)分析2025-08-08
Python爬蟲實(shí)現(xiàn)抓取京東店鋪信息及下載圖片功能示例
這篇文章主要介紹了Python爬蟲實(shí)現(xiàn)抓取京東店鋪信息及下載圖片功能,涉及Python頁面請求、響應(yīng)、解析等相關(guān)操作技巧,需要的朋友可以參考下2018-08-08
使用llama?Index幫你訓(xùn)練pdf的示例詳解
這篇文章主要為大家介紹了使用llama?Index?幫你訓(xùn)練pdf,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-03-03
Python分支語句與循環(huán)語句應(yīng)用實(shí)例分析
這篇文章主要介紹了Python分支語句與循環(huán)語句應(yīng)用,結(jié)合具體實(shí)例形式詳細(xì)分析了Python分支語句與循環(huán)語句各種常見應(yīng)用操作技巧與相關(guān)注意事項(xiàng),需要的朋友可以參考下2019-05-05

