Want to convert JSON data into a Python object? You can do it in one line, using named-tuple and object_hook:
1 2 3 4 5 6 7 8 |
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:
1 2 3 4 |
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.
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.