一、背景介绍
之前经常使用到JSON格式的基础数据,基本写死保存在代码之中,这样就存在难以维护的问题。那么有木有能够将这些JSON数据存储起来,并且能轻松读取和操作的方案吗?答案是肯定的。
二、具体实现
经过一番资料查询后,采用了TinyDB来实现。
数据示例如下:
# 节假日
off_workdays = {
'20240101': '元旦', # 周一
'20240210': '春节', # 周六
'20240211': '春节', # 周日
'20240212': '春节', # 周一
'20240213': '春节', # 周二
'20240214': '春节', # 周三
'20240215': '春节', # 周四
'20240216': '春节', # 周五
'20240217': '春节', # 周六
'20240404': '清明', # 周四
'20240405': '清明', # 周五
'20240406': '清明', # 周六
'20240501': '五一', # 周三
'20240502': '五一', # 周四
'20240503': '五一', # 周五
'20240504': '五一', # 周六
'20240505': '五一', # 周日
'20240608': '端午', # 周六
'20240609': '端午', # 周日
'20240610': '端午', # 周一
'20240915': '中秋', # 周日
'20240916': '中秋', # 周一
'20240917': '中秋', # 周二
'20241001': '国庆', # 周二
'20241002': '国庆', # 周三
'20241003': '国庆', # 周四
'20241004': '国庆', # 周五
'20241005': '国庆', # 周六
'20241006': '国庆', # 周日
'20241007': '国庆', # 周一
}
# 周末上班日
on_workdays = {
'20240204': '春节', # 周日
'20240218': '春节', # 周日
'20240407': '清明', # 周日
'20240428': '五一', # 周日
'20240511': '五一', # 周六
'20240929': '国庆', # 周日
'20241012': '国庆', # 周六
}
存
将以上JSON数据存储在workdays_and_holidays.json文件中
from tinydb import TinyDB, where
with TinyDB('workdays_and_holidays.json') as db: # 创建db
table = db.table('wah') # 创建表
# json的存储
table.insert({'year': 2024, 'type': 0, 'data': off_workdays, 'remark': '节假日'}) # 插入数据
table.insert({'year': 2024, 'type': 1, 'data': on_workdays, 'remark': '周末上班日'})
运行结果:
增
向JSON文件中插入数据
table.insert({'year': 2023, 'type': 2, 'data': '', 'remark': '测试数据删除'})
table.insert({'year': 2023, 'type': 3, 'data': {'month': 4}, 'remark': '测试数据修改'})
data = table.all() # 查询所有数据
print(data)
运行结果:
删
删除文件中type=2的数据
table.remove(where('type') == 2) # 删除type=2的数据
data = table.search(where('type') == 2) # 查询type=2的数据
print(data)
运行结果:
改
将type=3的数据中的data:{month:4}修改为data:{day:4}
data_before = table.search(where('data').day == 4) # 查询data.day=4的数据
print(f"修改前:{data_before}")
table.update({'data': {'day': 4}}, where('type') == 3) # 更新type=3的数据中data的值
data_after = table.search(where('data').day == 4) # 查询data.day=4的数据
print(f"修改后:{data_after}")
运行结果:
查
查询JSON文件中remark包含“上班”的数据和type不等于3的remark的值
data1 = table.search(where('remark').search('上班')) # 查询remark包含“上班”的数据
data2 = [i['remark'] for i in table.search(where('type') != 3)] # 查询type不为3的数据中的remark的值
print(data1)
print(data2)
运行结果:
三、初试体验
TinyDB能够实现快速的JSON数据的存储和检索,不需要建立独立的数据库,将数据存储在JSON文件中,简单易上手。