-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdpropjson.py
83 lines (73 loc) · 2.35 KB
/
dpropjson.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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import json
if 'JSONEncoder' not in json.__dict__:
from types import DictType, ListType
class Nothing:
"""Nothing is known of a value (this is prior to explicitly setting
the value)."""
def __iter__(self):
# Autofail.
class NothingIterator:
def __iter__(self):
return self
def next(self):
raise StopIteration
return NothingIterator()
def keys(self):
return []
class URI:
"""A URI reference."""
def __init__(self, value):
self.value = value
if 'JSONEncoder' in json.__dict__:
class DPropEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, Nothing):
return {'__nothing__': True}
elif isinstance(obj, URI):
return {'__uri__': True,
'uri': obj.value}
return json.JSONEncoder.default(self, obj)
else:
def DPropEncode(obj):
if isinstance(obj, Nothing):
return {'__nothing__': True}
elif isinstance(obj, URI):
return {'__uri__': True,
'uri': obj.value}
return obj
def DPropDecode(dct):
if '__nothing__' in dct:
return Nothing()
elif '__uri__' in dct:
return URI(dct['uri'])
return dct
if 'JSONEncoder' in json.__dict__:
def loads(str):
return json.loads(str, object_hook=DPropDecode)
else:
def loads(str):
def fixDicts(obj):
if isinstance(obj, DictType):
for key in obj.keys():
obj[key] = fixDicts(obj[key])
return DPropDecode(obj)
elif isinstance(obj, ListType):
for i in range(len(obj)):
obj[i] = fixDicts(obj[i])
return obj
obj = json.read(str)
return fixDicts(obj)
if 'JSONEncoder' in json.__dict__:
def dumps(obj):
return json.dumps(obj, cls=DPropEncoder)
else:
def dumps(obj):
def fixDicts(obj):
if isinstance(obj, DictType):
for key in obj.keys():
obj[key] = fixDicts(obj[key])
elif isinstance(obj, ListType):
for i in range(len(obj)):
obj[i] = fixDicts(obj[i])
return DPropEncode(obj)
return json.write(fixDicts(obj))