Is it possible to use json.loads()
in python to create an actual Python object instead of a dict value?
I would rather not have to do json_data['value_name']
and just to json_object.my_value
.
Is it possible to use json.loads()
in python to create an actual Python object instead of a dict value?
I would rather not have to do json_data['value_name']
and just to json_object.my_value
.
You can use Python alternative syntax for creating types:
attributes = {
'a': 12,
'b': 'there-is-a-value-here',
'greet': (lambda self: print("Hi, my a is {}".format(self.a)))
}
SomeCoolType = type("SomeCoolType", (), attributes)
someCoolInstance = SomeCoolType()
someCoolInstance.greet() # this prints "Hi, my a is 12"
The first argument is type name, second is tuple with parent classes, and the third is attributes dictionary. So, having that in mind, you can first decode JSON to dict, then construct a type from it, and then instantiate it:
d = json.loads(json_data)
T = type("JSON", (), d)
json_object = T()
Or, shorter:
json_object = type("JSON", (), json.loads(json_data))()
This simple approach will only change top-level dictionary to object; if you want to be able to call json_object.param.something.value
, you have to convert it via recursion (similar to shallow vs. deep copy):
def to_object(dictionary):
for key, value in dictionary.items():
if isinstance(value, dict): dictionary[key] = value
return type("JSON", (), dictionary)
json_object = to_object(json.loads(json_data))