Skip to content

Instantly share code, notes, and snippets.

@liluo
Last active August 29, 2015 14:06
Show Gist options
  • Save liluo/2d53628ee17114de72d4 to your computer and use it in GitHub Desktop.
Save liluo/2d53628ee17114de72d4 to your computer and use it in GitHub Desktop.
Utils
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