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)
相关推荐
Tony Bai4 小时前
高并发后端:坚守 Go,还是拥抱 Rust?
开发语言·后端·golang·rust
wjs20244 小时前
Swift 类型转换
开发语言
秃了也弱了。5 小时前
python实现定时任务:schedule库、APScheduler库
开发语言·python
Dfreedom.5 小时前
从 model(x) 到__call__:解密深度学习框架的设计基石
人工智能·pytorch·python·深度学习·call
weixin_440730505 小时前
java数组整理笔记
java·开发语言·笔记
weixin_425023005 小时前
Spring Boot 配置文件优先级详解
spring boot·后端·python
Thera7775 小时前
状态机(State Machine)详解:原理、优缺点与 C++ 实战示例
开发语言·c++
niucloud-admin6 小时前
java服务端——controller控制器
java·开发语言
‿hhh6 小时前
综合交通运行协调与应急指挥平台项目说明
java·ajax·npm·json·需求分析·个人开发·规格说明书
小徐Chao努力6 小时前
【Langchain4j-Java AI开发】06-工具与函数调用
java·人工智能·python