forked from teamtachyon/Quillpad-Server
-
Notifications
You must be signed in to change notification settings - Fork 0
/
demjson.py
executable file
·2138 lines (1911 loc) · 85.9 KB
/
demjson.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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
r""" A JSON data encoder and decoder.
This Python module implements the JSON (http://json.org/) data
encoding format; a subset of ECMAScript (aka JavaScript) for encoding
primitive data types (numbers, strings, booleans, lists, and
associative arrays) in a language-neutral simple text-based syntax.
It can encode or decode between JSON formatted strings and native
Python data types. Normally you would use the encode() and decode()
functions defined by this module, but if you want more control over
the processing you can use the JSON class.
This implementation tries to be as completely cormforming to all
intricacies of the standards as possible. It can operate in strict
mode (which only allows JSON-compliant syntax) or a non-strict mode
(which allows much more of the whole ECMAScript permitted syntax).
This includes complete support for Unicode strings (including
surrogate-pairs for non-BMP characters), and all number formats
including negative zero and IEEE 754 non-numbers such a NaN or
Infinity.
The JSON/ECMAScript to Python type mappings are:
---JSON--- ---Python---
null None
undefined undefined (note 1)
Boolean (true,false) bool (True or False)
Integer int or long (note 2)
Float float
String str or unicode ( "..." or u"..." )
Array [a, ...] list ( [...] )
Object {a:b, ...} dict ( {...} )
-- Note 1. an 'undefined' object is declared in this module which
represents the native Python value for this type when in
non-strict mode.
-- Note 2. some ECMAScript integers may be up-converted to Python
floats, such as 1e+40. Also integer -0 is converted to
float -0, so as to preserve the sign (which ECMAScript requires).
In addition, when operating in non-strict mode, several IEEE 754
non-numbers are also handled, and are mapped to specific Python
objects declared in this module:
NaN (not a number) nan (float('nan'))
Infinity, +Infinity inf (float('inf'))
-Infinity neginf (float('-inf'))
When encoding Python objects into JSON, you may use types other than
native lists or dictionaries, as long as they support the minimal
interfaces required of all sequences or mappings. This means you can
use generators and iterators, tuples, UserDict subclasses, etc.
To make it easier to produce JSON encoded representations of user
defined classes, if the object has a method named json_equivalent(),
then it will call that method and attempt to encode the object
returned from it instead. It will do this recursively as needed and
before any attempt to encode the object using it's default
strategies. Note that any json_equivalent() method should return
"equivalent" Python objects to be encoded, not an already-encoded
JSON-formatted string. There is no such aid provided to decode
JSON back into user-defined classes as that would dramatically
complicate the interface.
When decoding strings with this module it may operate in either
strict or non-strict mode. The strict mode only allows syntax which
is conforming to RFC 4627 (JSON), while the non-strict allows much
more of the permissible ECMAScript syntax.
The following are permitted when processing in NON-STRICT mode:
* Unicode format control characters are allowed anywhere in the input.
* All Unicode line terminator characters are recognized.
* All Unicode white space characters are recognized.
* The 'undefined' keyword is recognized.
* Hexadecimal number literals are recognized (e.g., 0xA6, 0177).
* String literals may use either single or double quote marks.
* Strings may contain \x (hexadecimal) escape sequences, as well as the
\v and \0 escape sequences.
* Lists may have omitted (elided) elements, e.g., [,,,,,], with
missing elements interpreted as 'undefined' values.
* Object properties (dictionary keys) can be of any of the
types: string literals, numbers, or identifiers (the later of
which are treated as if they are string literals)---as permitted
by ECMAScript. JSON only permits strings literals as keys.
Concerning non-strict and non-ECMAScript allowances:
* Octal numbers: If you allow the 'octal_numbers' behavior (which
is never enabled by default), then you can use octal integers
and octal character escape sequences (per the ECMAScript
standard Annex B.1.2). This behavior is allowed, if enabled,
because it was valid JavaScript at one time.
* Multi-line string literals: Strings which are more than one
line long (contain embedded raw newline characters) are never
permitted. This is neither valid JSON nor ECMAScript. Some other
JSON implementations may allow this, but this module considers
that behavior to be a mistake.
References:
* JSON (JavaScript Object Notation)
<http://json.org/>
* RFC 4627. The application/json Media Type for JavaScript Object Notation (JSON)
<http://www.ietf.org/rfc/rfc4627.txt>
* ECMA-262 3rd edition (1999)
<http://www.ecma-international.org/publications/files/ecma-st/ECMA-262.pdf>
* IEEE 754-1985: Standard for Binary Floating-Point Arithmetic.
<http://www.cs.berkeley.edu/~ejr/Projects/ieee754/>
"""
__author__ = "Deron Meranda <http://deron.meranda.us/>"
__date__ = "2008-12-17"
__version__ = "1.4"
__credits__ = """Copyright (c) 2006-2008 Deron E. Meranda <http://deron.meranda.us/>
Licensed under GNU LGPL 3.0 (GNU Lesser General Public License) or
later. See LICENSE.txt included with this software.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>
or <http://www.fsf.org/licensing/>.
"""
# ------------------------------
# useful global constants
content_type = 'application/json'
file_ext = 'json'
hexdigits = '0123456789ABCDEFabcdef'
octaldigits = '01234567'
# ----------------------------------------------------------------------
# Decimal and float types.
#
# If a JSON number can not be stored in a Python float without loosing
# precision and the Python has the decimal type, then we will try to
# use decimal instead of float. To make this determination we need to
# know the limits of the float type, but Python doesn't have an easy
# way to tell what the largest floating-point number it supports. So,
# we detemine the precision and scale of the float type by testing it.
try:
# decimal module was introduced in Python 2.4
import decimal
except ImportError:
decimal = None
def determine_float_precision():
"""Returns a tuple (significant_digits, max_exponent) for the float type.
"""
import math
# Just count the digits in pi. The last two decimal digits
# may only be partial digits, so discount for them.
whole, frac = repr(math.pi).split('.')
sigdigits = len(whole) + len(frac) - 2
# This is a simple binary search. We find the largest exponent
# that the float() type can handle without going infinite or
# raising errors.
maxexp = None
minv = 0; maxv = 1000
while True:
if minv+1 == maxv:
maxexp = minv - 1
break
elif maxv < minv:
maxexp = None
break
m = (minv + maxv) // 2
try:
f = repr(float( '1e+%d' % m ))
except ValueError:
f = None
else:
if not f or f[0] < '0' or f[0] > '9':
f = None
if not f:
# infinite
maxv = m
else:
minv = m
return sigdigits, maxexp
float_sigdigits, float_maxexp = determine_float_precision()
# ----------------------------------------------------------------------
# The undefined value.
#
# ECMAScript has an undefined value (similar to yet distinct from null).
# Neither Python or strict JSON have support undefined, but to allow
# JavaScript behavior we must simulate it.
class _undefined_class(object):
"""Represents the ECMAScript 'undefined' value."""
__slots__ = []
def __repr__(self):
return self.__module__ + '.undefined'
def __str__(self):
return 'undefined'
def __nonzero__(self):
return False
undefined = _undefined_class()
del _undefined_class
# ----------------------------------------------------------------------
# Non-Numbers: NaN, Infinity, -Infinity
#
# ECMAScript has official support for non-number floats, although
# strict JSON does not. Python doesn't either. So to support the
# full JavaScript behavior we must try to add them into Python, which
# is unfortunately a bit of black magic. If our python implementation
# happens to be built on top of IEEE 754 we can probably trick python
# into using real floats. Otherwise we must simulate it with classes.
def _nonnumber_float_constants():
"""Try to return the Nan, Infinity, and -Infinity float values.
This is unnecessarily complex because there is no standard
platform- independent way to do this in Python as the language
(opposed to some implementation of it) doesn't discuss
non-numbers. We try various strategies from the best to the
worst.
If this Python interpreter uses the IEEE 754 floating point
standard then the returned values will probably be real instances
of the 'float' type. Otherwise a custom class object is returned
which will attempt to simulate the correct behavior as much as
possible.
"""
try:
# First, try (mostly portable) float constructor. Works under
# Linux x86 (gcc) and some Unices.
nan = float('nan')
inf = float('inf')
neginf = float('-inf')
except ValueError:
try:
# Try the AIX (PowerPC) float constructors
nan = float('NaNQ')
inf = float('INF')
neginf = float('-INF')
except ValueError:
try:
# Next, try binary unpacking. Should work under
# platforms using IEEE 754 floating point.
import struct, sys
xnan = '7ff8000000000000'.decode('hex') # Quiet NaN
xinf = '7ff0000000000000'.decode('hex')
xcheck = 'bdc145651592979d'.decode('hex') # -3.14159e-11
# Could use float.__getformat__, but it is a new python feature,
# so we use sys.byteorder.
if sys.byteorder == 'big':
nan = struct.unpack('d', xnan)[0]
inf = struct.unpack('d', xinf)[0]
check = struct.unpack('d', xcheck)[0]
else:
nan = struct.unpack('d', xnan[::-1])[0]
inf = struct.unpack('d', xinf[::-1])[0]
check = struct.unpack('d', xcheck[::-1])[0]
neginf = - inf
if check != -3.14159e-11:
raise ValueError('Unpacking raw IEEE 754 floats does not work')
except (ValueError, TypeError):
# Punt, make some fake classes to simulate. These are
# not perfect though. For instance nan * 1.0 == nan,
# as expected, but 1.0 * nan == 0.0, which is wrong.
class nan(float):
"""An approximation of the NaN (not a number) floating point number."""
def __repr__(self): return 'nan'
def __str__(self): return 'nan'
def __add__(self,x): return self
def __radd__(self,x): return self
def __sub__(self,x): return self
def __rsub__(self,x): return self
def __mul__(self,x): return self
def __rmul__(self,x): return self
def __div__(self,x): return self
def __rdiv__(self,x): return self
def __divmod__(self,x): return (self,self)
def __rdivmod__(self,x): return (self,self)
def __mod__(self,x): return self
def __rmod__(self,x): return self
def __pow__(self,exp): return self
def __rpow__(self,exp): return self
def __neg__(self): return self
def __pos__(self): return self
def __abs__(self): return self
def __lt__(self,x): return False
def __le__(self,x): return False
def __eq__(self,x): return False
def __neq__(self,x): return True
def __ge__(self,x): return False
def __gt__(self,x): return False
def __complex__(self,*a): raise NotImplementedError('NaN can not be converted to a complex')
if decimal:
nan = decimal.Decimal('NaN')
else:
nan = nan()
class inf(float):
"""An approximation of the +Infinity floating point number."""
def __repr__(self): return 'inf'
def __str__(self): return 'inf'
def __add__(self,x): return self
def __radd__(self,x): return self
def __sub__(self,x): return self
def __rsub__(self,x): return self
def __mul__(self,x):
if x is neginf or x < 0:
return neginf
elif x == 0:
return nan
else:
return self
def __rmul__(self,x): return self.__mul__(x)
def __div__(self,x):
if x == 0:
raise ZeroDivisionError('float division')
elif x < 0:
return neginf
else:
return self
def __rdiv__(self,x):
if x is inf or x is neginf or x is nan:
return nan
return 0.0
def __divmod__(self,x):
if x == 0:
raise ZeroDivisionError('float divmod()')
elif x < 0:
return (nan,nan)
else:
return (self,self)
def __rdivmod__(self,x):
if x is inf or x is neginf or x is nan:
return (nan, nan)
return (0.0, x)
def __mod__(self,x):
if x == 0:
raise ZeroDivisionError('float modulo')
else:
return nan
def __rmod__(self,x):
if x is inf or x is neginf or x is nan:
return nan
return x
def __pow__(self, exp):
if exp == 0:
return 1.0
else:
return self
def __rpow__(self, x):
if -1 < x < 1: return 0.0
elif x == 1.0: return 1.0
elif x is nan or x is neginf or x < 0:
return nan
else:
return self
def __neg__(self): return neginf
def __pos__(self): return self
def __abs__(self): return self
def __lt__(self,x): return False
def __le__(self,x):
if x is self:
return True
else:
return False
def __eq__(self,x):
if x is self:
return True
else:
return False
def __neq__(self,x):
if x is self:
return False
else:
return True
def __ge__(self,x): return True
def __gt__(self,x): return True
def __complex__(self,*a): raise NotImplementedError('Infinity can not be converted to a complex')
if decimal:
inf = decimal.Decimal('Infinity')
else:
inf = inf()
class neginf(float):
"""An approximation of the -Infinity floating point number."""
def __repr__(self): return '-inf'
def __str__(self): return '-inf'
def __add__(self,x): return self
def __radd__(self,x): return self
def __sub__(self,x): return self
def __rsub__(self,x): return self
def __mul__(self,x):
if x is self or x < 0:
return inf
elif x == 0:
return nan
else:
return self
def __rmul__(self,x): return self.__mul__(self)
def __div__(self,x):
if x == 0:
raise ZeroDivisionError('float division')
elif x < 0:
return inf
else:
return self
def __rdiv__(self,x):
if x is inf or x is neginf or x is nan:
return nan
return -0.0
def __divmod__(self,x):
if x == 0:
raise ZeroDivisionError('float divmod()')
elif x < 0:
return (nan,nan)
else:
return (self,self)
def __rdivmod__(self,x):
if x is inf or x is neginf or x is nan:
return (nan, nan)
return (-0.0, x)
def __mod__(self,x):
if x == 0:
raise ZeroDivisionError('float modulo')
else:
return nan
def __rmod__(self,x):
if x is inf or x is neginf or x is nan:
return nan
return x
def __pow__(self,exp):
if exp == 0:
return 1.0
else:
return self
def __rpow__(self, x):
if x is nan or x is inf or x is inf:
return nan
return 0.0
def __neg__(self): return inf
def __pos__(self): return self
def __abs__(self): return inf
def __lt__(self,x): return True
def __le__(self,x): return True
def __eq__(self,x):
if x is self:
return True
else:
return False
def __neq__(self,x):
if x is self:
return False
else:
return True
def __ge__(self,x):
if x is self:
return True
else:
return False
def __gt__(self,x): return False
def __complex__(self,*a): raise NotImplementedError('-Infinity can not be converted to a complex')
if decimal:
neginf = decimal.Decimal('-Infinity')
else:
neginf = neginf(0)
return nan, inf, neginf
nan, inf, neginf = _nonnumber_float_constants()
del _nonnumber_float_constants
# ----------------------------------------------------------------------
# String processing helpers
unsafe_string_chars = '"\\' + ''.join([chr(i) for i in range(0x20)])
def skipstringsafe( s, start=0, end=None ):
i = start
#if end is None:
# end = len(s)
while i < end and s[i] not in unsafe_string_chars:
#c = s[i]
#if c in unsafe_string_chars:
# break
i += 1
return i
def skipstringsafe_slow( s, start=0, end=None ):
i = start
if end is None:
end = len(s)
while i < end:
c = s[i]
if c == '"' or c == '\\' or ord(c) <= 0x1f:
break
i += 1
return i
def extend_list_with_sep( orig_seq, extension_seq, sepchar='' ):
if not sepchar:
orig_seq.extend( extension_seq )
else:
for i, x in enumerate(extension_seq):
if i > 0:
orig_seq.append( sepchar )
orig_seq.append( x )
def extend_and_flatten_list_with_sep( orig_seq, extension_seq, separator='' ):
for i, part in enumerate(extension_seq):
if i > 0 and separator:
orig_seq.append( separator )
orig_seq.extend( part )
# ----------------------------------------------------------------------
# Unicode helpers
#
# JSON requires that all JSON implementations must support the UTF-32
# encoding (as well as UTF-8 and UTF-16). But earlier versions of
# Python did not provide a UTF-32 codec. So we must implement UTF-32
# ourselves in case we need it.
def utf32le_encode( obj, errors='strict' ):
"""Encodes a Unicode string into a UTF-32LE encoded byte string."""
import struct
try:
import cStringIO as sio
except ImportError:
import StringIO as sio
f = sio.StringIO()
write = f.write
pack = struct.pack
for c in obj:
n = ord(c)
if 0xD800 <= n <= 0xDFFF: # surrogate codepoints are prohibited by UTF-32
if errors == 'ignore':
continue
elif errors == 'replace':
n = ord('?')
else:
cname = 'U+%04X'%n
raise UnicodeError('UTF-32 can not encode surrogate characters',cname)
write( pack('<L', n) )
return f.getvalue()
def utf32be_encode( obj, errors='strict' ):
"""Encodes a Unicode string into a UTF-32BE encoded byte string."""
import struct
try:
import cStringIO as sio
except ImportError:
import StringIO as sio
f = sio.StringIO()
write = f.write
pack = struct.pack
for c in obj:
n = ord(c)
if 0xD800 <= n <= 0xDFFF: # surrogate codepoints are prohibited by UTF-32
if errors == 'ignore':
continue
elif errors == 'replace':
n = ord('?')
else:
cname = 'U+%04X'%n
raise UnicodeError('UTF-32 can not encode surrogate characters',cname)
write( pack('>L', n) )
return f.getvalue()
def utf32le_decode( obj, errors='strict' ):
"""Decodes a UTF-32LE byte string into a Unicode string."""
if len(obj) % 4 != 0:
raise UnicodeError('UTF-32 decode error, data length not a multiple of 4 bytes')
import struct
unpack = struct.unpack
chars = []
i = 0
for i in range(0, len(obj), 4):
seq = obj[i:i+4]
n = unpack('<L',seq)[0]
chars.append( unichr(n) )
return u''.join( chars )
def utf32be_decode( obj, errors='strict' ):
"""Decodes a UTF-32BE byte string into a Unicode string."""
if len(obj) % 4 != 0:
raise UnicodeError('UTF-32 decode error, data length not a multiple of 4 bytes')
import struct
unpack = struct.unpack
chars = []
i = 0
for i in range(0, len(obj), 4):
seq = obj[i:i+4]
n = unpack('>L',seq)[0]
chars.append( unichr(n) )
return u''.join( chars )
def auto_unicode_decode( s ):
"""Takes a string and tries to convert it to a Unicode string.
This will return a Python unicode string type corresponding to the
input string (either str or unicode). The character encoding is
guessed by looking for either a Unicode BOM prefix, or by the
rules specified by RFC 4627. When in doubt it is assumed the
input is encoded in UTF-8 (the default for JSON).
"""
if isinstance(s, unicode):
return s
if len(s) < 4:
return s.decode('utf8') # not enough bytes, assume default of utf-8
# Look for BOM marker
import codecs
bom2 = s[:2]
bom4 = s[:4]
a, b, c, d = map(ord, s[:4]) # values of first four bytes
if bom4 == codecs.BOM_UTF32_LE:
encoding = 'utf-32le'
s = s[4:]
elif bom4 == codecs.BOM_UTF32_BE:
encoding = 'utf-32be'
s = s[4:]
elif bom2 == codecs.BOM_UTF16_LE:
encoding = 'utf-16le'
s = s[2:]
elif bom2 == codecs.BOM_UTF16_BE:
encoding = 'utf-16be'
s = s[2:]
# No BOM, so autodetect encoding used by looking at first four bytes
# according to RFC 4627 section 3.
elif a==0 and b==0 and c==0 and d!=0: # UTF-32BE
encoding = 'utf-32be'
elif a==0 and b!=0 and c==0 and d!=0: # UTF-16BE
encoding = 'utf-16be'
elif a!=0 and b==0 and c==0 and d==0: # UTF-32LE
encoding = 'utf-32le'
elif a!=0 and b==0 and c!=0 and d==0: # UTF-16LE
encoding = 'utf-16le'
else: #if a!=0 and b!=0 and c!=0 and d!=0: # UTF-8
# JSON spec says default is UTF-8, so always guess it
# if we can't guess otherwise
encoding = 'utf8'
# Make sure the encoding is supported by Python
try:
cdk = codecs.lookup(encoding)
except LookupError:
if encoding.startswith('utf-32') \
or encoding.startswith('ucs4') \
or encoding.startswith('ucs-4'):
# Python doesn't natively have a UTF-32 codec, but JSON
# requires that it be supported. So we must decode these
# manually.
if encoding.endswith('le'):
unis = utf32le_decode(s)
else:
unis = utf32be_decode(s)
else:
raise JSONDecodeError('this python has no codec for this character encoding',encoding)
else:
# Convert to unicode using a standard codec
unis = s.decode(encoding)
return unis
def surrogate_pair_as_unicode( c1, c2 ):
"""Takes a pair of unicode surrogates and returns the equivalent unicode character.
The input pair must be a surrogate pair, with c1 in the range
U+D800 to U+DBFF and c2 in the range U+DC00 to U+DFFF.
"""
n1, n2 = ord(c1), ord(c2)
if n1 < 0xD800 or n1 > 0xDBFF or n2 < 0xDC00 or n2 > 0xDFFF:
raise JSONDecodeError('illegal Unicode surrogate pair',(c1,c2))
a = n1 - 0xD800
b = n2 - 0xDC00
v = (a << 10) | b
v += 0x10000
return unichr(v)
def unicode_as_surrogate_pair( c ):
"""Takes a single unicode character and returns a sequence of surrogate pairs.
The output of this function is a tuple consisting of one or two unicode
characters, such that if the input character is outside the BMP range
then the output is a two-character surrogate pair representing that character.
If the input character is inside the BMP then the output tuple will have
just a single character...the same one.
"""
n = ord(c)
if n < 0x10000:
return (unichr(n),) # in BMP, surrogate pair not required
v = n - 0x10000
vh = (v >> 10) & 0x3ff # highest 10 bits
vl = v & 0x3ff # lowest 10 bits
w1 = 0xD800 | vh
w2 = 0xDC00 | vl
return (unichr(w1), unichr(w2))
# ----------------------------------------------------------------------
# Type identification
def isnumbertype( obj ):
"""Is the object of a Python number type (excluding complex)?"""
return isinstance(obj, (int,long,float)) \
and not isinstance(obj, bool) \
or obj is nan or obj is inf or obj is neginf
def isstringtype( obj ):
"""Is the object of a Python string type?"""
if isinstance(obj, basestring):
return True
# Must also check for some other pseudo-string types
import types, UserString
return isinstance(obj, types.StringTypes) \
or isinstance(obj, UserString.UserString) \
or isinstance(obj, UserString.MutableString)
# ----------------------------------------------------------------------
# Numeric helpers
def decode_hex( hexstring ):
"""Decodes a hexadecimal string into it's integer value."""
# We don't use the builtin 'hex' codec in python since it can
# not handle odd numbers of digits, nor raise the same type
# of exceptions we want to.
n = 0
for c in hexstring:
if '0' <= c <= '9':
d = ord(c) - ord('0')
elif 'a' <= c <= 'f':
d = ord(c) - ord('a') + 10
elif 'A' <= c <= 'F':
d = ord(c) - ord('A') + 10
else:
raise JSONDecodeError('not a hexadecimal number',hexstring)
# Could use ((n << 4 ) | d), but python 2.3 issues a FutureWarning.
n = (n * 16) + d
return n
def decode_octal( octalstring ):
"""Decodes an octal string into it's integer value."""
n = 0
for c in octalstring:
if '0' <= c <= '7':
d = ord(c) - ord('0')
else:
raise JSONDecodeError('not an octal number',octalstring)
# Could use ((n << 3 ) | d), but python 2.3 issues a FutureWarning.
n = (n * 8) + d
return n
# ----------------------------------------------------------------------
# Exception classes.
class JSONError(ValueError):
"""Our base class for all JSON-related errors.
"""
def pretty_description(self):
err = self.args[0]
if len(self.args) > 1:
err += ': '
for anum, a in enumerate(self.args[1:]):
if anum > 1:
err += ', '
astr = repr(a)
if len(astr) > 20:
astr = astr[:20] + '...'
err += astr
return err
class JSONDecodeError(JSONError):
"""An exception class raised when a JSON decoding error (syntax error) occurs."""
class JSONEncodeError(JSONError):
"""An exception class raised when a python object can not be encoded as a JSON string."""
#----------------------------------------------------------------------
# The main JSON encoder/decoder class.
class JSON(object):
"""An encoder/decoder for JSON data streams.
Usually you will call the encode() or decode() methods. The other
methods are for lower-level processing.
Whether the JSON parser runs in strict mode (which enforces exact
compliance with the JSON spec) or the more forgiving non-string mode
can be affected by setting the 'strict' argument in the object's
initialization; or by assigning True or False to the 'strict'
property of the object.
You can also adjust a finer-grained control over strictness by
allowing or preventing specific behaviors. You can get a list of
all the available behaviors by accessing the 'behaviors' property.
Likewise the allowed_behaviors and prevented_behaviors list which
behaviors will be allowed and which will not. Call the allow()
or prevent() methods to adjust these.
"""
_escapes_json = { # character escapes in JSON
'"': '"',
'/': '/',
'\\': '\\',
'b': '\b',
'f': '\f',
'n': '\n',
'r': '\r',
't': '\t',
}
_escapes_js = { # character escapes in Javascript
'"': '"',
'\'': '\'',
'\\': '\\',
'b': '\b',
'f': '\f',
'n': '\n',
'r': '\r',
't': '\t',
'v': '\v',
'0': '\x00'
}
# Following is a reverse mapping of escape characters, used when we
# output JSON. Only those escapes which are always safe (e.g., in JSON)
# are here. It won't hurt if we leave questionable ones out.
_rev_escapes = {'\n': '\\n',
'\t': '\\t',
'\b': '\\b',
'\r': '\\r',
'\f': '\\f',
'"': '\\"',
'\\': '\\\\'}
def __init__(self, strict=False, compactly=True, escape_unicode=False):
"""Creates a JSON encoder/decoder object.
If 'strict' is set to True, then only strictly-conforming JSON
output will be produced. Note that this means that some types
of values may not be convertable and will result in a
JSONEncodeError exception.
If 'compactly' is set to True, then the resulting string will
have all extraneous white space removed; if False then the
string will be "pretty printed" with whitespace and indentation
added to make it more readable.
If 'escape_unicode' is set to True, then all non-ASCII characters
will be represented as a unicode escape sequence; if False then
the actual real unicode character will be inserted if possible.
The 'escape_unicode' can also be a function, which when called
with a single argument of a unicode character will return True
if the character should be escaped or False if it should not.
If you wish to extend the encoding to ba able to handle
additional types, you should subclass this class and override
the encode_default() method.
"""
import sys
self._set_strictness(strict)
self._encode_compactly = compactly
try:
# see if we were passed a predicate function
b = escape_unicode(u'A')
self._encode_unicode_as_escapes = escape_unicode
except (ValueError, NameError, TypeError):
# Just set to True or False. We could use lambda x:True
# to make it more consistent (always a function), but it
# will be too slow, so we'll make explicit tests later.
self._encode_unicode_as_escapes = bool(escape_unicode)
self._sort_dictionary_keys = True
# The following is a boolean map of the first 256 characters
# which will quickly tell us which of those characters never
# need to be escaped.
self._asciiencodable = [32 <= c < 128 and not self._rev_escapes.has_key(chr(c))
for c in range(0,255)]
def _set_strictness(self, strict):
"""Changes the strictness behavior.
Pass True to be very strict about JSON syntax, or False to be looser.
"""
self._allow_any_type_at_start = not strict
self._allow_all_numeric_signs = not strict
self._allow_comments = not strict
self._allow_control_char_in_string = not strict
self._allow_hex_numbers = not strict
self._allow_initial_decimal_point = not strict
self._allow_js_string_escapes = not strict
self._allow_non_numbers = not strict
self._allow_nonescape_characters = not strict # "\z" -> "z"
self._allow_nonstring_keys = not strict
self._allow_omitted_array_elements = not strict
self._allow_single_quoted_strings = not strict
self._allow_trailing_comma_in_literal = not strict
self._allow_undefined_values = not strict
self._allow_unicode_format_control_chars = not strict
self._allow_unicode_whitespace = not strict
# Always disable this by default
self._allow_octal_numbers = False
def allow(self, behavior):
"""Allow the specified behavior (turn off a strictness check).
The list of all possible behaviors is available in the behaviors property.
You can see which behaviors are currently allowed by accessing the
allowed_behaviors property.
"""
p = '_allow_' + behavior
if hasattr(self, p):
setattr(self, p, True)
else:
raise AttributeError('Behavior is not known',behavior)
def prevent(self, behavior):
"""Prevent the specified behavior (turn on a strictness check).
The list of all possible behaviors is available in the behaviors property.
You can see which behaviors are currently prevented by accessing the
prevented_behaviors property.
"""
p = '_allow_' + behavior
if hasattr(self, p):
setattr(self, p, False)
else:
raise AttributeError('Behavior is not known',behavior)
def _get_behaviors(self):
return sorted([ n[len('_allow_'):] for n in self.__dict__ \
if n.startswith('_allow_')])
behaviors = property(_get_behaviors,
doc='List of known behaviors that can be passed to allow() or prevent() methods')
def _get_allowed_behaviors(self):
return sorted([ n[len('_allow_'):] for n in self.__dict__ \
if n.startswith('_allow_') and getattr(self,n)])
allowed_behaviors = property(_get_allowed_behaviors,
doc='List of known behaviors that are currently allowed')
def _get_prevented_behaviors(self):
return sorted([ n[len('_allow_'):] for n in self.__dict__ \
if n.startswith('_allow_') and not getattr(self,n)])
prevented_behaviors = property(_get_prevented_behaviors,
doc='List of known behaviors that are currently prevented')
def _is_strict(self):
return not self.allowed_behaviors
strict = property(_is_strict, _set_strictness,
doc='True if adherence to RFC 4627 syntax is strict, or False is more generous ECMAScript syntax is permitted')
def isws(self, c):
"""Determines if the given character is considered as white space.
Note that Javscript is much more permissive on what it considers
to be whitespace than does JSON.
Ref. ECMAScript section 7.2
"""
if not self._allow_unicode_whitespace:
return c in ' \t\n\r'
else:
if not isinstance(c,unicode):