-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathjsonDict.py
More file actions
45 lines (38 loc) · 991 Bytes
/
jsonDict.py
File metadata and controls
45 lines (38 loc) · 991 Bytes
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# coding=utf-8
import json
class JsonDict(dict):
"""
General json object that allows attributes to be bound to and also behaves like a dict.
>>> jd = JsonDict(a=1, b='test')
>>> jd.a
1
>>> jd.b
'test'
>>> jd['b']
'test'
>>> jd.c
Traceback (most recent call last):
...
AttributeError: 'JsonDict' object has no attribute 'c'
>>> jd['c']
Traceback (most recent call last):
...
KeyError: 'c'
"""
def __getattr__(self, attr):
try:
return self[attr]
except KeyError:
raise AttributeError(r"'JsonDict' object has no attribute '%s'" % attr)
def __setattr__(self, attr, value):
self[attr] = value
def loads(string):
"""
Parse json string into JsonDict.
>>> r = loads(r'{"name":"Michael","score":95}')
>>> r.name
u'Michael'
>>> r['score']
95
"""
return json.loads(string, object_hook=lambda pairs: JsonDict(pairs.iteritems()))