欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 财经 > 产业 > python处理json文件

python处理json文件

2025/2/7 8:30:40 来源:https://blog.csdn.net/weixin_49577420/article/details/145482242  浏览:    关键词:python处理json文件

1 普通类处理:

import jsonclass MotorModel:def __init__(self, name: str, rate: int, value: int):self.name = nameself.rate = rateself.value = value# 示例 motor_list
motor_list = [MotorModel('motor100', 1, 100),MotorModel('motor200', 2, 50),MotorModel('motor300', 3, 110),
]# 将 MotorModel 对象转换为字典
def motor_to_dict(motor):return {'name': motor.name,'rate': motor.rate,'value': motor.value}# 将 motor_list 转换为字典列表
motor_dict_list = [motor_to_dict(motor) for motor in motor_list]# 保存为 JSON 文件
with open('motors.json', 'w') as f:json.dump(motor_dict_list, f, indent=4)# 从字典创建 MotorModel 对象
def dict_to_motor(motor_dict):return MotorModel(name=motor_dict['name'],rate=motor_dict['rate'],value=motor_dict['value'])# 从 JSON 文件中读取数据
with open('motors.json', 'r') as f:motor_dict_list = json.load(f)# 将字典列表转换为 MotorModel 对象列表
motor_list_loaded = [dict_to_motor(motor_dict) for motor_dict in motor_dict_list]# 打印加载的对象列表
for motor in motor_list_loaded:print(f"Name: {motor.name}, Rate: {motor.rate}, Value: {motor.value}")

2 数据类处理(推荐)

from dataclasses import dataclass, asdict
import json
from typing import List@dataclass
class Model:Name: strId: intValue: strRate: intdef WriteFile(models: List[Model], filename: str) -> None:"""将 Model 对象列表写入 JSON 文件"""# 将 Model 对象列表转换为字典列表models_dict = [asdict(model) for model in models]# 写入 JSON 文件with open(filename, 'w') as f:json.dump(models_dict, f, indent=4)def ReadFile(filename: str) -> List[Model]:"""从 JSON 文件读取并解析为 Model 对象列表"""# 从 JSON 文件读取字典列表with open(filename, 'r') as f:models_dict = json.load(f)# 将字典列表转换为 Model 对象列表models = [Model(**model_dict) for model_dict in models_dict]return models# 示例数据
models = [Model(Name="motor100", Id=1, Value="100", Rate=10),Model(Name="motor200", Id=2, Value="200", Rate=20),Model(Name="motor300", Id=3, Value="300", Rate=30),
]# 写入 JSON 文件
#WriteFile(models, 'models.json')# 从 JSON 文件读取
loaded_models = ReadFile('models.json')# 打印读取的数据
for model in loaded_models:print(model)

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com