python将json实例化为class文件 写入.py文件

python将json实例化为class文件 写入.py文件create_class.py

python 复制代码
import json


class Command:
    def handle(self, *args, **kwargs):
        json_file = kwargs['json_file']
        class_name = kwargs['class_name']
        output_file = kwargs['output_file']

        with open(json_file, 'r') as f:
            data = json.load(f)

        class_def = f"class {class_name}:\n"
        for key, value in data.items():
            if not isinstance(value, str):
                class_def += f"    {key} = {value}\n"
            else:
                class_def += f"    {key} = '{value}'\n"

        with open(output_file, 'w') as f:
            f.write(class_def)


if __name__ == "__main__":
    c = Command()
    c.handle(json_file='config.json', class_name="TestClass", output_file='test_01.py')

config.json

powershell 复制代码
{
    "name": "John Doe",
    "age": 31,
    "is_student": false,
    "courses": [
        "Math",
        "Physics",
        "Chemistry",
        "Biology"
    ]
}

运行后即可得到

文件 test_01.py

python 复制代码
class TestClass:
    name = 'John Doe'
    age = 31
    is_student = False
    courses = ['Math', 'Physics', 'Chemistry', 'Biology']

还可以定义模版文件,然后直接写成.py文件

文件:config4_bx.py

python 复制代码
import json

# JSON 数据字符串
json_data = '''
{
    "name": "John Doe",
    "age": 30,
    "is_student": false,
    "courses": ["Math", "Physics", "Chemistry"]
}
'''

# 解析 JSON 数据
data = json.loads(json_data)

# 定义类名
class_name = "Person"
func_name = "BYD_A88"


def func1():
    print('111')


# 生成类定义的模板
class_template = f"""
from src.common.config4_bx import func1

class {class_name}:
    def __init__(self):
{"".join(f'        self.{k} = "{v}"\n' if isinstance(v, str) else f'        self.{k} = {v}\n' for k, v in data.items())}

    def __str__(self):
        return f"{class_name}(name={data.get('name')}, age={data.get('age')}, is_student={data.get('is_student')}, courses={data.get('courses')})"
        
    def test_{func_name}_smoke(self):
        func1()
"""

# 写入 Python 文件
with open('test_person.py', 'w') as file:
    file.write(class_template)

# 输出生成的类定义
print(class_template)
相关推荐
red润40 分钟前
let obj = { foo: 1 };为什么Reflect.get(obj, ‘foo‘, { foo: 2 }); // 输出 1?
开发语言·javascript·ecmascript
froginwe111 小时前
PHP MySQL Delete 操作详解
开发语言
Nep&Preception2 小时前
vasp计算弹性常数
开发语言·python
DIY机器人工房2 小时前
一个基于 epoll 实现的多路复用 TCP 服务器程序,相比 select 和 poll 具有更高的效率
开发语言·嵌入式硬件·php·嵌入式·diy机器人工房
费弗里2 小时前
Python全栈应用开发神器fac 0.4.0新版本升级指南&更新日志
python·dash
Ice__Cai2 小时前
Python 基础详解:数据类型(Data Types)—— 程序的“数据基石”
开发语言·后端·python·数据类型
lilv663 小时前
python中用xlrd、xlwt读取和写入Excel中的日期值
开发语言·python·excel
程序员果子3 小时前
macOS Python 安装
python·macos
LetsonH3 小时前
⭐CVPR2025 RoboBrain:机器人操作的统一大脑模型[特殊字符]
人工智能·python·深度学习·计算机视觉·机器人
阿巴~阿巴~4 小时前
构造函数:C++对象初始化的核心机制
开发语言·c++