Skip to content

Instantly share code, notes, and snippets.

@mrbitsdcf
Created June 16, 2024 12:17
Show Gist options
  • Save mrbitsdcf/4555b081f8d9098b324a95c3943389dd to your computer and use it in GitHub Desktop.
Save mrbitsdcf/4555b081f8d9098b324a95c3943389dd to your computer and use it in GitHub Desktop.
Convert json or dict structures to an object.
import json
class DynamicObject:
def __init__(self, data):
self._load_data(data)
def _load_data(self, data):
for key, value in data.items():
if isinstance(value, dict):
value = DynamicObject(value)
elif isinstance(value, list):
value = [
DynamicObject(item) if isinstance(item, dict) else item
for item in value
]
setattr(self, key, value)
def __repr__(self):
return f"{self.__class__.__name__}({self.__dict__})"
def convert_to_object(data):
if isinstance(data, str):
data = json.loads(data)
elif not isinstance(data, dict):
raise ValueError("Data must be a JSON string or dictionary")
return DynamicObject(data)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment