-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathejson.py
403 lines (305 loc) · 10.6 KB
/
ejson.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
"""
EJSON is a complete implementation of EJSON according to Meteor version 0.6.
See README.md for details.
Homepage and documentation: https://github.com/kkurian/ejson
Copyright (c) 2013 Kerry Ivan Kurian
License: MIT (see LICENSE for details)
"""
__author__ = 'Kerry Ivan Kurian'
__version__ = '0.0'
__license__ = 'MIT'
import json
from time import mktime
from copy import deepcopy
from collections import OrderedDict
from base64 import b64encode, b64decode
from abc import ABCMeta, abstractmethod
from datetime import datetime, timedelta
from json import JSONEncoder, JSONDecoder
class CustomType:
__metaclass__ = ABCMeta
@abstractmethod
def clone(self):
raise NotImplementedError
@abstractmethod
def equals(self, other):
raise NotImplementedError
@abstractmethod
def __eq__(self, other):
raise NotImplementedError
@abstractmethod
def type_name(self):
raise NotImplementedError
@abstractmethod
def to_json_value(self):
raise NotImplementedError
class EJSONEncoder(JSONEncoder):
_default = JSONEncoder.default
def default(self, obj):
if not isinstance(obj, CustomType):
return super(EJSONEncoder, self).default(obj)
return obj.to_json_value()
class EJSONDecoder(JSONDecoder):
_custom_type_factories = dict()
def __init__(self, encoding, object_hook=None):
if object_hook:
# Decode inputs into regular (unordered) dicts using the
# object_hook to handle custom JSON objects.
super(EJSONDecoder, self).__init__(
encoding,
object_hook=object_hook)
else:
# Decode inputs into OrderedDict's.
super(EJSONDecoder, self).__init__(
encoding,
object_pairs_hook=EJSONDecoder.default)
@classmethod
def from_json_value(cls, val):
try:
key, value = val.iteritems().next()
return cls._custom_type_factories[key](val)
except (AttributeError, KeyError):
# AttributeError means that val is not a dict and therefore not
# a CustomType. KeyError means that no custom factory exists for
# the val and therefore it is not a CustomType. In either case,
# just return the val.
return val
@classmethod
def register_custom_type(cls, custom_type_name, factory):
if custom_type_name in cls._custom_type_factories:
msg = 'name collision: custom type "{}" is already in use.'
raise ValueError(msg.format(custom_type_name))
cls._custom_type_factories[custom_type_name] = factory
@classmethod
def default(cls, pairs):
"""
Receives inputs like:
[(u'b', 1), (u'c', 2)]
[(u'a', [(u'b', 1), (u'c', 2)]), (u'd', [(u'e', 3)])]
[(u'$date', 1358205756553)]
Returns results like:
OrderedDict([(u'b', 1), (u'c', 2)])
OrderedDict([(u'a', [(u'b', 1), (u'c', 2)]), (u'd', [(u'e', 3)])])
Date(2013, 1, 14, 16, 22, 36, 553000)
"""
result = OrderedDict()
if len(pairs) == 1:
key, value = pairs[0]
if any(k == key for k in cls._custom_type_factories):
return cls._custom_type_factories[key]({key: value})
for pair in pairs:
key, value = pair
if isinstance(value, list):
result[key] = cls.default(value)
else:
result[key] = value
return result
class EJSONUnorderedDecoder(EJSONDecoder):
def __init__(self, encoding):
super(EJSONUnorderedDecoder, self).__init__(
encoding,
object_hook=EJSONUnorderedDecoder.default)
@classmethod
def default(cls, dict_):
if len(dict_) == 1 and \
any(k in dict_ for k in cls._custom_type_factories):
key, value = dict_.iteritems().next()
return cls._custom_type_factories[key]({key: value})
return dict_
def parse(str_):
return loads(str_)
def loads(str_):
return json.loads(str_, cls=EJSONDecoder)
def stringify(val):
return dumps(val)
def dumps(val):
return json.dumps(val, cls=EJSONEncoder)
def from_json_value(val):
return EJSONDecoder.from_json_value(val)
def to_json_value(val):
if isinstance(val, CustomType):
return val.to_json_value()
return val
def equals(a, b, key_order_sensitive=False):
if not key_order_sensitive:
a = json.loads(dumps(a), cls=EJSONUnorderedDecoder)
b = json.loads(dumps(b), cls=EJSONUnorderedDecoder)
if hasattr(a, '__eq__'):
return a.__eq__(b)
return _deep_eq(a, b)
def clone(val):
return deepcopy(val)
# No need to def deepcopy(). See `from copy import deepcopy`, above.
def new_binary(size):
return Binary(size)
def is_binary(x):
return isinstance(x, Binary)
def add_type(name, factory):
EJSONDecoder.register_custom_type(name, factory)
### Builtin CustomType's
DATE_TAG = '$date'
BINARY_TAG = '$binary'
## Date
class Date(datetime, CustomType):
def clone(self):
return deepcopy(self)
def equals(self, other):
return self.__eq__(other)
# __eq__ is defined by datetime.
def type_name(self):
return DATE_TAG
def to_json_value(self):
msecs_since_epoch = \
int(mktime(self.timetuple())*1e3 + self.microsecond/1e3)
return {DATE_TAG: msecs_since_epoch}
def date_factory(json_dict):
if len(json_dict) != 1:
raise ValueError('Too many keys in {}.'.format(json_dict))
try:
timestamp = json_dict[DATE_TAG] / 1000.0 # milliseconds --> seconds
return Date.fromtimestamp(timestamp)
except Exception as e:
raise ValueError(e)
## Binary
class Binary(bytearray, CustomType):
def clone(self):
return deepcopy(self)
def equals(self, other):
return self.__eq__(other)
# __eq__ is defined by datetime.
def type_name(self):
return BINARY_TAG
def to_json_value(self):
return {BINARY_TAG: b64encode(self)}
def binary_factory(json_dict):
if len(json_dict) != 1:
raise ValueError('Too many keys in {}.'.format(json_dict))
try:
return Binary(b64decode(json_dict[BINARY_TAG]))
except Exception as e:
return ValueError(e)
## Install Date and Binary
add_type(DATE_TAG, date_factory)
add_type(BINARY_TAG, binary_factory)
### Third-party code
##
# deep_eq
#
# From: https://gist.github.com/samuraisam/901117
#
# Copyright (c) 2010-2013 Samuel Sutch [[email protected]]
# License: MIT (see LICENSE for details)
_default_fudge = timedelta(seconds=0, microseconds=0, days=0)
def _deep_eq(_v1, _v2, datetime_fudge=_default_fudge, _assert=False):
"""
Tests for deep equality between two python data structures recursing
into sub-structures if necessary. Works with all python types including
iterators and generators. This function was dreampt up to test API responses
but could be used for anything. Be careful. With deeply nested structures
you may blow the stack.
Options:
datetime_fudge => this is a datetime.timedelta object which, when
comparing dates, will accept values that differ
by the number of seconds specified
_assert => passing yes for this will raise an assertion error
when values do not match, instead of returning
false (very useful in combination with pdb)
Doctests included:
>>> x1, y1 = ({'a': 'b'}, {'a': 'b'})
>>> deep_eq(x1, y1)
True
>>> x2, y2 = ({'a': 'b'}, {'b': 'a'})
>>> deep_eq(x2, y2)
False
>>> x3, y3 = ({'a': {'b': 'c'}}, {'a': {'b': 'c'}})
>>> deep_eq(x3, y3)
True
>>> x4, y4 = ({'c': 't', 'a': {'b': 'c'}}, {'a': {'b': 'n'}, 'c': 't'})
>>> deep_eq(x4, y4)
False
>>> x5, y5 = ({'a': [1,2,3]}, {'a': [1,2,3]})
>>> deep_eq(x5, y5)
True
>>> x6, y6 = ({'a': [1,'b',8]}, {'a': [2,'b',8]})
>>> deep_eq(x6, y6)
False
>>> x7, y7 = ('a', 'a')
>>> deep_eq(x7, y7)
True
>>> x8, y8 = (['p','n',['asdf']], ['p','n',['asdf']])
>>> deep_eq(x8, y8)
True
>>> x9, y9 = (['p','n',['asdf',['omg']]], ['p', 'n', ['asdf',['nowai']]])
>>> deep_eq(x9, y9)
False
>>> x10, y10 = (1, 2)
>>> deep_eq(x10, y10)
False
>>> deep_eq((str(p) for p in xrange(10)), (str(p) for p in xrange(10)))
True
>>> str(deep_eq(range(4), range(4)))
'True'
>>> deep_eq(xrange(100), xrange(100))
True
>>> deep_eq(xrange(2), xrange(5))
False
>>> import datetime
>>> from datetime import datetime as dt
>>> d1, d2 = (dt.now(), dt.now() + datetime.timedelta(seconds=4))
>>> deep_eq(d1, d2)
False
>>> deep_eq(d1, d2, datetime_fudge=datetime.timedelta(seconds=5))
True
"""
_deep_eq = functools.partial(deep_eq, datetime_fudge=datetime_fudge,
_assert=_assert)
def _check_assert(R, a, b, reason=''):
if _assert and not R:
assert 0, "an assertion has failed in deep_eq (%s) %s != %s" % (
reason, str(a), str(b))
return R
def _deep_dict_eq(d1, d2):
k1, k2 = (sorted(d1.keys()), sorted(d2.keys()))
if k1 != k2: # keys should be exactly equal
return _check_assert(False, k1, k2, "keys")
return _check_assert(operator.eq(sum(_deep_eq(d1[k], d2[k])
for k in k1),
len(k1)), d1, d2, "dictionaries")
def _deep_iter_eq(l1, l2):
if len(l1) != len(l2):
return _check_assert(False, l1, l2, "lengths")
return _check_assert(operator.eq(sum(_deep_eq(v1, v2)
for v1, v2 in zip(l1, l2)),
len(l1)), l1, l2, "iterables")
def op(a, b):
_op = operator.eq
if type(a) == datetime and type(b) == datetime:
s = datetime_fudge.seconds
t1, t2 = (mktime(a.timetuple()), mktime(b.timetuple()))
l = t1 - t2
l = -l if l > 0 else l
return _check_assert((-s if s > 0 else s) <= l, a, b, "dates")
return _check_assert(_op(a, b), a, b, "values")
c1, c2 = (_v1, _v2)
# guard against strings because they are iterable and their
# elements yield iterables infinitely.
# I N C E P T I O N
for t in types.StringTypes:
if isinstance(_v1, t):
break
else:
if isinstance(_v1, types.DictType):
op = _deep_dict_eq
else:
try:
c1, c2 = (list(iter(_v1)), list(iter(_v2)))
except TypeError:
c1, c2 = _v1, _v2
else:
op = _deep_iter_eq
return op(c1, c2)
# End deep_eq
##
if __name__ == '__main__':
import doctest
doctest.testmod()