Skip to content

Instantly share code, notes, and snippets.

@Pacheco95
Last active December 21, 2022 18:14
Show Gist options
  • Save Pacheco95/4671edc777e1af3b68a588cddca47714 to your computer and use it in GitHub Desktop.
Save Pacheco95/4671edc777e1af3b68a588cddca47714 to your computer and use it in GitHub Desktop.
Python serializable type that allow dot notation access
import json
from json import JSONEncoder
from typing import Iterator, Mapping
class StructEncoder(JSONEncoder):
def default(self, o):
return o.__dict__ if isinstance(o, Struct) else super().default(o)
class Struct(Mapping):
def __init__(self, **kwargs):
for key, value in kwargs.items():
if isinstance(value, dict):
self.__dict__[key] = Struct(**value)
elif isinstance(value, list):
self.__dict__[key] = [
Struct(**item) if isinstance(item, dict) else item for item in value
]
else:
self.__dict__[key] = value
def __getitem__(self, k):
pass
def __len__(self) -> int:
pass
def __iter__(self):
pass
some_dict = {
"a_list": [
{
"a_nested_list": ["wow"]
}
],
"just_a_value": True,
"an_object": {
"a_nested_object": {
"a_nested_object_with_a_nested_list": [
"you got it!"
]
}
}
}
my_struct = Struct(**some_dict)
print(json.dumps(my_struct, indent=2, cls=StructEncoder))
# Prints:
# {
# "a_list": [
# {
# "a_nested_list": [
# "wow"
# ]
# }
# ],
# "just_a_value": true,
# "an_object": {
# "a_nested_object": {
# "a_nested_object_with_a_nested_list": [
# "you got it!"
# ]
# }
# }
# }
print(my_struct.an_object.a_nested_object.a_nested_object_with_a_nested_list[0] == "you got it!")
# True
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment