Skip to content

Instantly share code, notes, and snippets.

@mijdavis2
Created August 19, 2021 12:06
Show Gist options
  • Save mijdavis2/b92bcc3ebcd06873c0f83d0ae1d89092 to your computer and use it in GitHub Desktop.
Save mijdavis2/b92bcc3ebcd06873c0f83d0ae1d89092 to your computer and use it in GitHub Desktop.
Convert dict to js style object in Python 3
"""
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