Even more fun with dict

Amaro Vita, 5 ноября 2020 г. 11:07


import json

data = """
{"menu": {
  "id": "file",
  "value": "File",
  "popup": {
    "menuitem": [
      {"value": "New", "@click": "CreateNewDoc()"},
      {"value": "Open", "@click": "OpenDoc()"},
      {"value": "Close", "@click": "CloseDoc()"}
    ]
  }
}}
"""


class ddict(dict):

    @classmethod
    def assign(cls, obj):
        if isinstance(obj, list):
            return [ddict.assign(x) for x in obj]
        elif isinstance(obj, dict):
            return ddict((k, ddict.assign(v)) for k, v in obj. items())
        else:
            return obj

    def __getitem__(self, key):
        try:
            return super().__getitem__(key)
        except KeyError:
            v = self[key] = ddict()
            return v

    def __getattr__(self, key):
        try:
            return self.__getitem__(key)
        except KeyError:
            raise AttributeError(key)

    def __setattr__(self, key, value):
        try:
            return self.__setitem__(key, value)
        except KeyError:
            raise AttributeError(key)

    def __delattr__(self, key):
        try:
            return self.__delitem__(key)
        except KeyError:
            raise AttributeError(key)

d = ddict.assign(json.loads(data))     
print(d.menu.value)
print(d.menu.popup.menuitem[1].value)
print(d.menu.popup.menuitem[1]['@click'])

File
Open
OpenDoc()