Created
October 23, 2012 01:57
-
-
Save pydsigner/3936231 to your computer and use it in GitHub Desktop.
Lame JSON Demo
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 | |
def as_cool_class(dct): | |
if '_is_cool_class' in dct: | |
return CoolClass(dct['spam'], dct['num']) | |
return dct | |
class CoolClass(object): | |
def __init__(self, spam, num): | |
self.spam = spam | |
self.num = num | |
class ICanLoadItEncoder(json.JSONEncoder): | |
def default(self, obj): | |
if isinstance(obj, CoolClass): | |
return {'_is_cool_class': True, 'spam': obj.spam, 'num': obj.num} | |
return json.JSONEncoder.default(self, obj) | |
cool = CoolClass('I am a Cool Class!!!1!', 42) | |
print cool.spam, cool.num | |
encoded = json.dumps(cool, cls=ICanLoadItEncoder) | |
print encoded | |
decoded = json.loads(encoded, object_hook=as_cool_class) | |
print decoded.spam, decoded.num |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment