Last active
May 20, 2021 06:57
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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