gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 07:32:47 25 4
gpt4 key购买 nike

我嵌套了如下的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)

关于python - 将嵌套的 Json 转换为 Python 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43776223/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com