Last active
August 29, 2015 13:56
-
-
Save drawcode/8931613 to your computer and use it in GitHub Desktop.
JSON to 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
# using namedtuple and object_hook: | |
import json | |
from collections import namedtuple | |
data = '{"name": "John Smith", "hometown": {"name": "New York", "id": 123}}' | |
# Parse JSON into an object with attributes corresponding to dict keys. | |
x = json.loads(data, object_hook=lambda d: namedtuple('X', d.keys())(*d.values())) | |
print x.name, x.hometown.name, x.hometown.id | |
#or, to reuse this easily: | |
def _json_object_hook(d): return namedtuple('X', d.keys())(*d.values()) | |
def json2obj(data): return json.loads(data, object_hook=_json_object_hook) | |
x = json2obj(data) | |
# If you want it to handle keys that aren't good attribute names, check out namedtuple's rename parameter. | |
# http://docs.python.org/2/library/collections.html#collections.namedtuple |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment