Created
March 28, 2014 13:30
-
-
Save whosaysni/9832747 to your computer and use it in GitHub Desktop.
Dictionary with JSON-serialized internal buffer. Placed in the Public Domain.
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
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