Ich habe json wie untenKonvertieren von Nested Json in Python Objekt
verschachtelt{
"product" : "name",
"protocol" : "scp",
"read_logs" : {
"log_type" : "failure",
"log_url" : "htttp:url"
}
}
Ich versuche, Python-Klasse-Objekt mit dem folgenden Code zu erstellen.
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()
Aber wird der object_hook die load_json Aufruf rekursiv und die Klasse Config init genannt zweimal wird. Das endgültige Objekt, das ich erstellt habe, enthält daher nicht die verschachtelten JSON-Daten.
Gibt es eine Möglichkeit, das gesamte verschachtelte JSON-Objekt in einer einzigen Python-Klasse zu lesen?
Dank
namedtuples Verwendung ist nicht die semantisch beste Option, keine neue 'namedtuple's Schaffung zu erwähnen ziemlich ist langsam aufgrund der Klassenerstellung. – AKX