Skip to main content
 首页 » 编程设计

python之将嵌套的 Json 转换为 Python 对象

2025年05月04日14me-sa

我嵌套了如下的json

{ 
"product" : "name", 
"protocol" : "scp", 
"read_logs" : { 
    "log_type" : "failure", 
    "log_url" : "htttp:url" 
    } 
} 

我正在尝试使用以下代码创建 Python 类对象。

import json 
class Config (object): 
    """ 
    Argument: JSON Object from the configuration file. 
    """ 
   def __init__(self, attrs): 
        if 'log_type' in attrs: 
            self.log_type = attrs['log_type'] 
            self.log_url = attrs['log_url'] 
        else: 
           self.product = attrs["product"] 
           self.protocol = attrs["protocol"] 
   def __str__(self): 
       return "%s;%s" %(self.product, self.log_type) 
 
   def get_product(self): 
        return self.product 
 
   def get_logurl(self): 
       return self.log_url 
 
class ConfigLoader (object): 
    ''' 
        Create a confiuration loaded which can read JSON config files 
    ''' 
    def load_config (self, attrs): 
        with open (attrs) as data_file: 
            config = json.load(data_file, object_hook=load_json) 
        return config 
 
def load_json (json_object): 
    return Config (json_object) 
 
loader = ConfigLoader() 
config = loader.load_config('../config/product_config.json') 
 
print config.get_protocol() 

但是,object_hook 正在递归调用 load_json 并且类配置 init 被调用了两次。所以我创建的最终对象不包含嵌套的 JSON 数据。

有没有办法将整个嵌套的 JSON 对象读取到单个 Python 类中?

谢谢

请您参考如下方法:

Pankaj Singhal 想法的变体,但使用“通用”命名空间类而不是命名元组:

import json 
 
class Generic: 
    @classmethod 
    def from_dict(cls, dict): 
        obj = cls() 
        obj.__dict__.update(dict) 
        return obj 
 
data = '{"product": "name", "read_logs": {"log_type": "failure", "log_url": "123"}}' 
 
x = json.loads(data, object_hook=Generic.from_dict) 
print(x.product, x.read_logs.log_type, x.read_logs.log_url)