Created
August 19, 2021 12:06
-
-
Save mijdavis2/b92bcc3ebcd06873c0f83d0ae1d89092 to your computer and use it in GitHub Desktop.
Convert dict to js style object in Python 3
This file contains hidden or 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
""" | |
Not actually sure when this would be a good idea, | |
but had the idea when porting some js/node to python. | |
Inspired by https://stackoverflow.com/questions/6578986/how-to-convert-json-data-into-a-python-object | |
""" | |
import json | |
from types import SimpleNamespace | |
class CustomNamespace(SimpleNamespace): | |
def __getattr__(self, name): | |
return None | |
data = '{"name": "John Smith", "hometown": {"name": "New York", "id": 123}}' | |
x = json.loads(data, object_hook=lambda d: CustomNamespace(**d)) | |
print(x.name) | |
# "John Smith" | |
print(x.hometown.name) | |
# "New York" | |
print(x.hobbies) | |
# None |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment