Skip to content

Instantly share code, notes, and snippets.

@whosaysni
Created March 28, 2014 13:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save whosaysni/9832747 to your computer and use it in GitHub Desktop.
Save whosaysni/9832747 to your computer and use it in GitHub Desktop.
Dictionary with JSON-serialized internal buffer. Placed in the Public Domain.
from json import dumps, loads
from UserDict import DictMixin
class JsonSerializedDict(DictMixin):
"""
>>> JSD = JsonSerializedDict
>>> d = JSD()
>>> print d
{}
>>> d['asdf'] = 42
>>> print d.json
{"asdf": 42}
>>> print d.items()
[(u'asdf', 42)]
>>> print 'asdf' in d
True
>>> d.pop('asdf')
42
>>> d.get('abc', 'def')
'def'
"""
def __init__(self, json='{}'):
loads(json) # assert if it's valid json
self.json = json
@property
def as_dict(self):
return loads(self.json)
def __getitem__(self, key):
return self.as_dict[key]
def __setitem__(self, key, value):
d = self.as_dict
d[key] = value
self.json = dumps(d)
def __delitem__(self, key):
d = self.as_dict
del d[key]
self.json = dumps(d)
def keys(self):
return self.as_dict.keys()
if __name__=='__main__':
from doctest import testmod
testmod()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment