-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathorderDict.py
29 lines (23 loc) · 1002 Bytes
/
orderDict.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
from collections import OrderedDict
import json
class OrderDict(OrderedDict):
def __init__(self, *args, **kwds):
OrderedDict.__init__(self, *args, **kwds)
def dumps(self):
return '{"data":%s, "index":%s}' % (json.dumps(self), json.dumps(self.keys()))
def loads(self, obj):
if isinstance(obj, str) or isinstance(obj, unicode):
str_json = json.loads(obj)
elif isinstance(obj, dict):
str_json = obj
if 'data' not in str_json or 'index' not in str_json or \
not isinstance(str_json['data'], dict):
raise ValueError(u"%s is not a vaild OrderDict dumps string or dict" % unicode(obj))
else:
raise ValueError(u"%s is not a vaild OrderDict dumps string or dict" % unicode(obj))
for item in str_json['index']:
self[item] = str_json['data'].get(item)
return self
b = OrderDict({"a": 1, "b": 2})
b.dumps()
print b