Skip to content

Instantly share code, notes, and snippets.

@cjhanks
Created April 2, 2013 00:19
Show Gist options
  • Save cjhanks/5288924 to your computer and use it in GitHub Desktop.
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.
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