Last active
August 29, 2015 14:06
-
-
Save liluo/2d53628ee17114de72d4 to your computer and use it in GitHub Desktop.
Utils
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
from collections import namedtuple | |
def json2object(data): | |
""" | |
>>> json2object("a") | |
'a' | |
>>> data = {"a": 100, "b": 200} | |
>>> obj = json2object(data) | |
>>> obj.a | |
100 | |
>>> obj.b | |
200 | |
>>> data2 = {"a": 100, | |
... "b": {"c": 101, | |
... "d": {"e": 201, | |
... "f": [1, 2, 3, 4] | |
... } | |
... } | |
... } | |
>>> obj2 = json2object(data2) | |
>>> obj2.b.d | |
JSON2Object(e=201, f=[1, 2, 3, 4]) | |
>>> obj2.b.d.f | |
[1, 2, 3, 4] | |
""" | |
if isinstance(data, dict): | |
JSON2Object = namedtuple('JSON2Object', data.keys()) | |
return JSON2Object(*map(json2object, data.values())) | |
return data |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment