-
Notifications
You must be signed in to change notification settings - Fork 76
/
demjson.py
6281 lines (5431 loc) · 242 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).
-- Note 3. numbers requiring more significant digits than can be
represented by the Python float type will be converted into a
Python Decimal type, from the standard 'decimal' module.
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 7159 (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 7159. The application/json Media Type for JavaScript Object Notation (JSON)
<http://www.ietf.org/rfc/rfc7159.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/>"
__homepage__ = "http://deron.meranda.us/python/demjson/"
__date__ = "2015-12-22"
__version__ = "2.2.4"
__version_info__ = ( 2, 2, 4 ) # Will be converted into a namedtuple below
__credits__ = """Copyright (c) 2006-2015 Deron E. Meranda <http://deron.meranda.us/>
Licensed under GNU LGPL (GNU Lesser General Public License) version 3.0
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/>.
"""
# ----------------------------------------------------------------------
# Set demjson version
try:
from collections import namedtuple as _namedtuple
__version_info__ = _namedtuple('version_info', ['major', 'minor', 'micro'])( *__version_info__ )
except ImportError:
raise ImportError("demjson %s requires a Python 2.6 or later" % __version__ )
version, version_info = __version__, __version_info__
# Determine Python version
_py_major, _py_minor = None, None
def _get_pyver():
global _py_major, _py_minor
import sys
vi = sys.version_info
try:
_py_major, _py_minor = vi.major, vi.minor
except AttributeError:
_py_major, _py_minor = vi[0], vi[1]
_get_pyver()
# ----------------------------------------------------------------------
# Useful global constants
content_type = 'application/json'
file_ext = 'json'
class _dummy_context_manager(object):
"""A context manager that does nothing on entry or exit."""
def __enter__(self):
pass
def __exit__(self, exc_type, exc_val, exc_tb):
return False
_dummy_context_manager = _dummy_context_manager()
# ----------------------------------------------------------------------
# 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_limits( number_type=float ):
"""Determines the precision and range of the given float type.
The passed in 'number_type' argument should refer to the type of
floating-point number. It should either be the built-in 'float',
or decimal context or constructor; i.e., one of:
# 1. FLOAT TYPE
determine_float_limits( float )
# 2. DEFAULT DECIMAL CONTEXT
determine_float_limits( decimal.Decimal )
# 3. CUSTOM DECIMAL CONTEXT
ctx = decimal.Context( prec=75 )
determine_float_limits( ctx )
Returns a named tuple with components:
( significant_digits,
max_exponent,
min_exponent )
Where:
* significant_digits -- maximum number of *decimal* digits
that can be represented without any loss of precision.
This is conservative, so if there are 16 1/2 digits, it
will return 16, not 17.
* max_exponent -- The maximum exponent (power of 10) that can
be represented before an overflow (or rounding to
infinity) occurs.
* min_exponent -- The minimum exponent (negative power of 10)
that can be represented before either an underflow
(rounding to zero) or a subnormal result (loss of
precision) occurs. Note this is conservative, as
subnormal numbers are excluded.
"""
if decimal:
numeric_exceptions = (ValueError,decimal.Overflow,decimal.Underflow)
else:
numeric_exceptions = (ValueError,)
if decimal and number_type == decimal.Decimal:
number_type = decimal.DefaultContext
if decimal and isinstance(number_type, decimal.Context):
# Passed a decimal Context, extract the bound creator function.
create_num = number_type.create_decimal
decimal_ctx = decimal.localcontext(number_type)
is_zero_or_subnormal = lambda n: n.is_zero() or n.is_subnormal()
elif number_type == float:
create_num = number_type
decimal_ctx = _dummy_context_manager
is_zero_or_subnormal = lambda n: n==0
else:
raise TypeError("Expected a float type, e.g., float or decimal context")
with decimal_ctx:
zero = create_num('0.0')
# Find signifianct digits by comparing floats of increasing
# number of digits, differing in the last digit only, until
# they numerically compare as being equal.
sigdigits = None
n = 0
while True:
n = n + 1
pfx = '0.' + '1'*n
a = create_num( pfx + '0')
for sfx in '123456789': # Check all possible last digits to
# avoid any partial-decimal.
b = create_num( pfx + sfx )
if (a+zero) == (b+zero):
sigdigits = n
break
if sigdigits:
break
# Find exponent limits. First find order of magnitude and
# then use a binary search to find the exact exponent.
base = '1.' + '1'*(sigdigits-1)
base0 = '1.' + '1'*(sigdigits-2)
minexp, maxexp = None, None
for expsign in ('+','-'):
minv = 0; maxv = 10
# First find order of magnitude of exponent limit
while True:
try:
s = base + 'e' + expsign + str(maxv)
s0 = base0 + 'e' + expsign + str(maxv)
f = create_num( s ) + zero
f0 = create_num( s0 ) + zero
except numeric_exceptions:
f = None
if not f or not str(f)[0].isdigit() or is_zero_or_subnormal(f) or f==f0:
break
else:
minv = maxv
maxv = maxv * 10
# Now do a binary search to find exact limit
while True:
if minv+1 == maxv:
if expsign=='+':
maxexp = minv
else:
minexp = minv
break
elif maxv < minv:
if expsign=='+':
maxexp = None
else:
minexp = None
break
m = (minv + maxv) // 2
try:
s = base + 'e' + expsign + str(m)
s0 = base0 + 'e' + expsign + str(m)
f = create_num( s ) + zero
f0 = create_num( s0 ) + zero
except numeric_exceptions:
f = None
else:
if not f or not str(f)[0].isdigit():
f = None
elif is_zero_or_subnormal(f) or f==f0:
f = None
if not f:
# infinite
maxv = m
else:
minv = m
return _namedtuple('float_limits', ['significant_digits', 'max_exponent', 'min_exponent'])( sigdigits, maxexp, -minexp )
float_sigdigits, float_maxexp, float_minexp = determine_float_limits( float )
# For backwards compatibility with older demjson versions:
def determine_float_precision():
v = determine_float_limits( float )
return ( v.significant_digits, v.max_exponent )
# ----------------------------------------------------------------------
# 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()
syntax_error = _undefined_class() # same as undefined, but has separate identity
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 necessarily 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
# ----------------------------------------------------------------------
# Integers
class json_int( (1L).__class__ ): # Have to specify base this way to satisfy 2to3
"""A subclass of the Python int/long that remembers its format (hex,octal,etc).
Initialize it the same as an int, but also accepts an additional keyword
argument 'number_format' which should be one of the NUMBER_FORMAT_* values.
n = json_int( x[, base, number_format=NUMBER_FORMAT_DECIMAL] )
"""
def __new__(cls, *args, **kwargs):
if 'number_format' in kwargs:
number_format = kwargs['number_format']
del kwargs['number_format']
if number_format not in (NUMBER_FORMAT_DECIMAL, NUMBER_FORMAT_HEX, NUMBER_FORMAT_OCTAL, NUMBER_FORMAT_LEGACYOCTAL, NUMBER_FORMAT_BINARY):
raise TypeError("json_int(): Invalid value for number_format argument")
else:
number_format = NUMBER_FORMAT_DECIMAL
obj = super(json_int,cls).__new__(cls,*args,**kwargs)
obj._jsonfmt = number_format
return obj
@property
def number_format(self):
"""The original radix format of the number"""
return self._jsonfmt
def json_format(self):
"""Returns the integer value formatted as a JSON literal"""
fmt = self._jsonfmt
if fmt == NUMBER_FORMAT_HEX:
return format(self, '#x')
elif fmt == NUMBER_FORMAT_OCTAL:
return format(self, '#o')
elif fmt == NUMBER_FORMAT_BINARY:
return format(self, '#b')
elif fmt == NUMBER_FORMAT_LEGACYOCTAL:
if self==0:
return '0' # For some reason Python's int doesn't do '00'
elif self < 0:
return '-0%o' % (-self)
else:
return '0%o' % self
else:
return str(self)
# ----------------------------------------------------------------------
# String processing helpers
def skipstringsafe( s, start=0, end=None ):
i = start
#if end is None:
# end = len(s)
unsafe = helpers.unsafe_string_chars
while i < end and s[i] not in unsafe:
#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 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 UTF-32
# ----------------------------------------------------------------------
def _make_raw_bytes( byte_list ):
"""Takes a list of byte values (numbers) and returns a bytes (Python 3) or string (Python 2)
"""
if _py_major >= 3:
b = bytes( byte_list )
else:
b = ''.join(chr(n) for n in byte_list)
return b
import codecs
class utf32(codecs.CodecInfo):
"""Unicode UTF-32 and UCS4 encoding/decoding support.
This is for older Pythons whch did not have UTF-32 codecs.
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.
See http://en.wikipedia.org/wiki/UTF-32
"""
BOM_UTF32_BE = _make_raw_bytes([ 0, 0, 0xFE, 0xFF ]) #'\x00\x00\xfe\xff'
BOM_UTF32_LE = _make_raw_bytes([ 0xFF, 0xFE, 0, 0 ]) #'\xff\xfe\x00\x00'
@staticmethod
def lookup( name ):
"""A standard Python codec lookup function for UCS4/UTF32.
If if recognizes an encoding name it returns a CodecInfo
structure which contains the various encode and decoder
functions to use.
"""
ci = None
name = name.upper()
if name in ('UCS4BE','UCS-4BE','UCS-4-BE','UTF32BE','UTF-32BE','UTF-32-BE'):
ci = codecs.CodecInfo( utf32.utf32be_encode, utf32.utf32be_decode, name='utf-32be')
elif name in ('UCS4LE','UCS-4LE','UCS-4-LE','UTF32LE','UTF-32LE','UTF-32-LE'):
ci = codecs.CodecInfo( utf32.utf32le_encode, utf32.utf32le_decode, name='utf-32le')
elif name in ('UCS4','UCS-4','UTF32','UTF-32'):
ci = codecs.CodecInfo( utf32.encode, utf32.decode, name='utf-32')
return ci
@staticmethod
def encode( obj, errors='strict', endianness=None, include_bom=True ):
"""Encodes a Unicode string into a UTF-32 encoded byte string.
Returns a tuple: (bytearray, num_chars)
The errors argument should be one of 'strict', 'ignore', or 'replace'.
The endianness should be one of:
* 'B', '>', or 'big' -- Big endian
* 'L', '<', or 'little' -- Little endien
* None -- Default, from sys.byteorder
If include_bom is true a Byte-Order Mark will be written to
the beginning of the string, otherwise it will be omitted.
"""
import sys, struct
# Make a container that can store bytes
if _py_major >= 3:
f = bytearray()
write = f.extend
def tobytes():
return bytes(f)
else:
try:
import cStringIO as sio
except ImportError:
import StringIO as sio
f = sio.StringIO()
write = f.write
tobytes = f.getvalue
if not endianness:
endianness = sys.byteorder
if endianness.upper()[0] in ('B>'):
big_endian = True
elif endianness.upper()[0] in ('L<'):
big_endian = False
else:
raise ValueError("Invalid endianness %r: expected 'big', 'little', or None" % endianness)
pack = struct.pack
packspec = '>L' if big_endian else '<L'
num_chars = 0
if include_bom:
if big_endian:
write( utf32.BOM_UTF32_BE )
else:
write( utf32.BOM_UTF32_LE )
num_chars += 1
for pos, c in enumerate(obj):
n = ord(c)
if 0xD800 <= n <= 0xDFFF: # surrogate codepoints are prohibited by UTF-32
if errors == 'ignore':
pass
elif errors == 'replace':
n = 0xFFFD
else:
raise UnicodeEncodeError('utf32',obj,pos,pos+1,"surrogate code points from U+D800 to U+DFFF are not allowed")
write( pack( packspec, n) )
num_chars += 1
return (tobytes(), num_chars)
@staticmethod
def utf32le_encode( obj, errors='strict', include_bom=False ):
"""Encodes a Unicode string into a UTF-32LE (little endian) encoded byte string."""
return utf32.encode( obj, errors=errors, endianness='L', include_bom=include_bom )
@staticmethod
def utf32be_encode( obj, errors='strict', include_bom=False ):
"""Encodes a Unicode string into a UTF-32BE (big endian) encoded byte string."""
return utf32.encode( obj, errors=errors, endianness='B', include_bom=include_bom )
@staticmethod
def decode( obj, errors='strict', endianness=None ):
"""Decodes a UTF-32 byte string into a Unicode string.
Returns tuple (bytearray, num_bytes)
The errors argument shold be one of 'strict', 'ignore',
'replace', 'backslashreplace', or 'xmlcharrefreplace'.
The endianness should either be None (for auto-guessing), or a
word that starts with 'B' (big) or 'L' (little).
Will detect a Byte-Order Mark. If a BOM is found and endianness
is also set, then the two must match.
If neither a BOM is found nor endianness is set, then big
endian order is assumed.
"""
import struct, sys
maxunicode = sys.maxunicode
unpack = struct.unpack
# Detect BOM
if obj.startswith( utf32.BOM_UTF32_BE ):
bom_endianness = 'B'
start = len(utf32.BOM_UTF32_BE)
elif obj.startswith( utf32.BOM_UTF32_LE ):
bom_endianness = 'L'
start = len(utf32.BOM_UTF32_LE)
else:
bom_endianness = None
start = 0
num_bytes = start
if endianness == None:
if bom_endianness == None:
endianness = sys.byteorder.upper()[0] # Assume platform default
else:
endianness = bom_endianness
else:
endianness = endianness[0].upper()
if bom_endianness and endianness != bom_endianness:
raise UnicodeDecodeError('utf32',obj,0,start,'BOM does not match expected byte order')
# Check for truncated last character
if ((len(obj)-start) % 4) != 0:
raise UnicodeDecodeError('utf32',obj,start,len(obj),
'Data length not a multiple of 4 bytes')
# Start decoding characters
chars = []
packspec = '>L' if endianness=='B' else '<L'
i = 0
for i in range(start, len(obj), 4):
seq = obj[i:i+4]
n = unpack( packspec, seq )[0]
num_bytes += 4
if n > maxunicode or (0xD800 <= n <= 0xDFFF):
if errors == 'strict':
raise UnicodeDecodeError('utf32',obj,i,i+4,'Invalid code point U+%04X' % n)
elif errors == 'replace':
chars.append( unichr(0xFFFD) )
elif errors == 'backslashreplace':
if n > 0xffff:
esc = "\\u%04x" % (n,)
else:
esc = "\\U%08x" % (n,)
for esc_c in esc:
chars.append( esc_c )
elif errors == 'xmlcharrefreplace':
esc = "&#%d;" % (n,)
for esc_c in esc:
chars.append( esc_c )
else: # ignore
pass
else:
chars.append( helpers.safe_unichr(n) )
return (u''.join( chars ), num_bytes)
@staticmethod
def utf32le_decode( obj, errors='strict' ):
"""Decodes a UTF-32LE (little endian) byte string into a Unicode string."""
return utf32.decode( obj, errors=errors, endianness='L' )
@staticmethod
def utf32be_decode( obj, errors='strict' ):
"""Decodes a UTF-32BE (big endian) byte string into a Unicode string."""
return utf32.decode( obj, errors=errors, endianness='B' )
# ----------------------------------------------------------------------
# Helper functions
# ----------------------------------------------------------------------
def _make_unsafe_string_chars():
import unicodedata
unsafe = []
for c in [unichr(i) for i in range(0x100)]:
if c == u'"' or c == u'\\' \
or unicodedata.category( c ) in ['Cc','Cf','Zl','Zp']:
unsafe.append( c )
return u''.join( unsafe )
class helpers(object):
"""A set of utility functions."""
hexdigits = '0123456789ABCDEFabcdef'
octaldigits = '01234567'
unsafe_string_chars = _make_unsafe_string_chars()
import sys
maxunicode = sys.maxunicode
always_use_custom_codecs = False # If True use demjson's codecs
# before system codecs. This
# is mainly here for testing.
javascript_reserved_words = frozenset([
# Keywords (plus "let") (ECMAScript 6 section 11.6.2.1)
'break','case','catch','class','const','continue',
'debugger','default','delete','do','else','export',
'extends','finally','for','function','if','import',
'in','instanceof','let','new','return','super',
'switch','this','throw','try','typeof','var','void',
'while','with','yield',
# Future reserved words (ECMAScript 6 section 11.6.2.2)
'enum','implements','interface','package',
'private','protected','public','static',
# null/boolean literals
'null','true','false'
])
@staticmethod
def make_raw_bytes( byte_list ):
"""Constructs a byte array (bytes in Python 3, str in Python 2) from a list of byte values (0-255).