【发布时间】:2017-10-02 05:45:45
【问题描述】:
我有如下嵌套的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 并且 Class Config init 被调用了两次。所以我创建的最终对象不包含嵌套的 JSON 数据。
有没有办法将整个嵌套的 JSON 对象读入单个 Python 类?
谢谢
【问题讨论】: