This is how you can create a nested object from JSON (similarly to how PHP does that). To create object tree from JSON (rather, parsed JSON, which is just a Python structure), write the following class:
class Nested:
def __new__(cls, structure):
self = super(Nested, cls).__new__(cls)
if type(structure) is dict:
self.__dict__ = {key: Nested(structure[key]) for key in structure}
elif type(structure) is list:
self = [Nested(item) for item in structure]
else:
self = structure
return self
and call it from your parsed JSON. For example:
import json
s = json.dumps({'a': 1, 'b': {'c': [1, 2, {'d': 3}], 'e': {'f': 'g'}}})
result = Nested(json.loads(s))
print(result.a) # 1
print(result.b.c) # [1, 2, <__main__.Nested object at 0x00000297A983D828>]
print(result.b.c[0]) # 1
print(result.b.c[2].d) # 3
Here is what is how the class works:
__new__
is invoked before anything else. Here we construct an instance of an object (empty)
If new is list, we replace self with list of nested objects, so that Nested({'a': [1, 2, 3]).a
is equal to [Nested(1), Nested(2), Nested(3)]
(which also equals to just [1, 2, 3]
, see number 4)
If new is dict, for each key we create a property with the same name and assign Nested(dict[key])
to it.
If any other type, just assign value to self (replace self
with value) so that Nested({'a': ['b', 'c', 'd']}).a[0]
equals 'b'
, not Nested(..)