将嵌套的 Json 转换为 Python 对象

Pra*_*een 5 python json

我嵌套了 json 如下

{
"product" : "name",
"protocol" : "scp",
"read_logs" : {
    "log_type" : "failure",
    "log_url" : "htttp:url"
    }
}
Run Code Online (Sandbox Code Playgroud)

我正在尝试使用以下代码创建 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()
Run Code Online (Sandbox Code Playgroud)

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

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

谢谢

AKX*_*AKX 9

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)
Run Code Online (Sandbox Code Playgroud)