Created
April 2, 2013 00:19
-
-
Save cjhanks/5288924 to your computer and use it in GitHub Desktop.
Allows a dictionary to act as an object and be serializable to JSON. Used for making JSON object behave like python objects.
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 | |
class MetaJson(dict): | |
""" | |
Allows a dictionary to act as an object and be serializable to JSON. Used | |
for making JSON object behave like python objects. | |
""" | |
def __init__(self, d = dict()): | |
dict.__init__(self, | |
{k: MetaJson(v) if isinstance(v, dict) else v for (k, v) in d.items()} | |
) | |
def __getattr__(self, key): | |
return dict.__getitem__(self, key) | |
def __setattr__(self, key, val): | |
if isinstance(val, dict): | |
val = MetaJson(val) | |
dict.__setattr__(self, key, val) | |
def __str__(self): | |
return json.dumps(self.serialize()) | |
def serialize(self): | |
ret = {} | |
for k in self.__dict__.keys(): | |
if isinstance(ret, MetaJson): | |
ret[k] = self.__dict__[k].serialize() | |
else: | |
ret[k] = self.__dict__[k] | |
return ret |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment