You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python自定义类读取嵌套JSON文件生成指定属性数组的方法

JSON配置解析类修正方案

原代码问题点

  • 键名拼写错误:JSON输入配置节点键为input,原代码误写为inputs,无法读取到对应配置
  • 数据类型处理错误:JSON中output、input字段为键值对字典结构,不是列表,直接map遍历只能拿到外层键名,无法获取min、max、selected等内层属性
  • 语法错误:__init__方法参数分隔符误写为点(self. args应为self, args),类方法缩进不符合Python规范
  • 逻辑缺失:from_dict方法未接收外层键作为实例id,无法生成带id属性的配置对象
  • 命名不规范:类名output首字母未大写,不符合Python类命名约定,易和实例变量混淆

修正后完整代码

class Output:
    def __init__(self, config_id, min_val, max_val):
        self.id = config_id
        self.min = min_val
        self.max = max_val

    @classmethod
    def from_dict(cls, config_id, value_dict):
        return cls(config_id, value_dict["min"], value_dict["max"])


class Input:
    def __init__(self, config_id, selected):
        self.id = config_id
        self.selected = selected

    @classmethod
    def from_dict(cls, config_id, value_dict):
        return cls(config_id, value_dict["selected"])


class ProductConfig(dict):
    def __init__(self, args):
        dict.__init__(self, args)
        field_config = args.get("field", {})
        
        # 遍历输出配置字典生成实例列表
        output_config = field_config.get("output", {})
        self.outputs = [
            Output.from_dict(output_id, output_val) 
            for output_id, output_val in output_config.items()
        ]
        
        # 遍历输入配置字典生成实例列表
        input_config = field_config.get("input", {})
        self.inputs = [
            Input.from_dict(input_id, input_val) 
            for input_id, input_val in input_config.items()
        ]


# 调用示例(替换为你自己的JSON文件读取逻辑即可)
if __name__ == "__main__":
    import json
    # 读取本地JSON文件可放开下方注释
    # with open("your_config.json", "r", encoding="utf-8") as f:
    #     json_data = json.load(f)
    json_data = {
        "field": {
            "output": {
                "Product": { "min": 26, "max": 80 },
                "Range": { "min": 0.01, "max": 0.04 }
            },
            "input": {
                "Powder": { "selected": True },
                "liquids": { "selected": True },
                "solids": { "selected": True }
            }
        }
    }
    config = ProductConfig(json_data)

实现效果

实例化ProductConfig后:

  • config.outputs为对象数组,每个对象包含id、min、max三个属性,对应JSON中output节点下的每一项配置
  • config.inputs为对象数组,每个对象包含id、selected两个属性,对应JSON中input节点下的每一项配置
    完全匹配预期的读取结构。

内容的提问来源于stack exchange,提问作者zsh_18

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.28 23:01:10