Created
February 5, 2013 00:13
-
-
Save abl/4711000 to your computer and use it in GitHub Desktop.
Classy JSON encoding/decoding with some fancy features.
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
import json, re | |
class MyObject: | |
pass | |
class MyExtension(MyObject): | |
pass | |
class Object: | |
pass | |
class ClassyEncoder(json.JSONEncoder): | |
def default(self, obj): | |
if isinstance(obj, MyObject): | |
key = '__%s__' % obj.__class__.__name__ | |
return { key: obj.__dict__ } | |
return json.JSONEncoder.default(self, obj) | |
def ClassyDecoder(dct): | |
class_regex = ClassyDecoder.class_regex | |
if len(dct) == 1: | |
type_name, value = dct.items()[0] | |
if class_regex.match(type_name): | |
type_name = type_name[2:-2] #Remove the __ __ | |
t = globals()[type_name] | |
i = t() | |
for k,v in value.items(): | |
i.__dict__[k] = v | |
return i | |
return dct | |
ClassyDecoder.class_regex = re.compile("__[^_]+__") | |
f = MyExtension() | |
f.myField = "fieldValue" | |
s = ClassyEncoder().encode(f) | |
print "JSON Encoding:" | |
print repr(s) | |
print "Decoded object:" | |
c = json.loads(s, object_hook=ClassyDecoder) | |
print c | |
print "myField:" | |
print c.myField |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment