Last active
December 15, 2015 21:19
-
-
Save tokibito/5325207 to your computer and use it in GitHub Desktop.
object_hook parameter for json module.
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
# coding: utf-8 | |
import json | |
DATA = """ | |
{ | |
"attr1": "foo", | |
"attr2": "bar", | |
"_class": "Foo", | |
"attr3": { | |
"attr3_1": "spam", | |
"attr3_2": "egg", | |
"_class": "Bar" | |
} | |
} | |
""" | |
class Base(object): | |
def __init__(self, **kwargs): | |
for key, value in kwargs.items(): | |
setattr(self, key, value) | |
def __repr__(self): | |
s = "<%s: %s>" % ( | |
self.__class__.__name__, | |
", ".join("%s=%s" % | |
(key, value) for key, value in self.__dict__.items())) | |
return s | |
class Foo(Base): | |
pass | |
class Bar(Base): | |
pass | |
def hook(dct): | |
class_name = dct.get('_class') | |
if class_name == 'Foo': | |
return Foo(**dct) | |
elif class_name == 'Bar': | |
return Bar(**dct) | |
return dct | |
def main(): | |
""" | |
>>> main() | |
<Foo: _class=Foo, attr2=bar, attr3=<Bar: attr3_2=egg, attr3_1=spam, _class=Bar>, attr1=foo> | |
""" | |
result = json.loads(DATA, object_hook=hook) | |
print result | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment