Skip to content

Instantly share code, notes, and snippets.

@25b3nk
Last active May 20, 2021 06:57
Show Gist options
  • Save 25b3nk/f071af1392f11ff14fb53f27773d6f3d to your computer and use it in GitHub Desktop.
Save 25b3nk/f071af1392f11ff14fb53f27773d6f3d to your computer and use it in GitHub Desktop.
This class, converts nested python dictionary to object. Stackoverflow answer link: https://stackoverflow.com/a/67608295/5258060
class Dict2Obj:
def __init__(self, json_data):
self.convert(json_data)
def convert(self, json_data):
if not isinstance(json_data, dict):
return
for key in json_data:
if not isinstance(json_data[key], dict):
self.__dict__.update({key: json_data[key]})
else:
self.__dict__.update({ key: Dict2Obj(json_data[key])})
if __name__ == "__main__":
json_data = {"a": {"b": 2}, "c": 3}
out_obj = Dict2Obj(json_data)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment