Skip to content

Instantly share code, notes, and snippets.

@abl
Created February 5, 2013 00:13
Show Gist options
  • Save abl/4711000 to your computer and use it in GitHub Desktop.
Save abl/4711000 to your computer and use it in GitHub Desktop.
Classy JSON encoding/decoding with some fancy features.
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