Created
April 12, 2019 15:08
-
-
Save Pebaz/60be59ea9f003349b725ed2fe30bd81a to your computer and use it in GitHub Desktop.
Turn JSON into Python Object
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
""" | |
Building a Python object from JSON isn't as straightforward as it looks. | |
SimpleNamespace only allows you to access fields that are valid variable | |
names. This poses a problem for JSON that contains invalid characters. | |
Here is my solution: | |
``` | |
# Doesn't work: | |
>>> data = json.loads(some_str, object_hook=lambda d: SimpleNamespace(**d)) | |
>>> print(data.foo.bar.%some$string&that*isn't#valid!python) | |
# BetterNamespace Solution: | |
>>> data = json.loads(some_str, object_hook=lambda d: BetterNamespace(**d)) | |
>>> print(data.foo.bar['%some$string&that*isn't#valid!python']) | |
``` | |
""" | |
from types import SimpleNamespace | |
import requests | |
class BetterNamespace(SimpleNamespace): | |
def __getitem__(self, key): | |
return getattr(self, key) | |
obj_maker = lambda d: BetterNamespace(**d) | |
text = requests.get('...').text | |
data = json.loads(text, object_hook=obj_maker) | |
# Supports Arbitrary Strings! | |
print(data.paths['/my/endpoint'].get.parameters) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment