Edit File by line
/home/barbar84/www/wp-conte.../plugins/sujqvwi/AnonR/smanonr..../lib64/python2..../json
File: encoder.py
"""Implementation of JSONEncoder
[0] Fix | Delete
"""
[1] Fix | Delete
import re
[2] Fix | Delete
[3] Fix | Delete
try:
[4] Fix | Delete
from _json import encode_basestring_ascii as c_encode_basestring_ascii
[5] Fix | Delete
except ImportError:
[6] Fix | Delete
c_encode_basestring_ascii = None
[7] Fix | Delete
try:
[8] Fix | Delete
from _json import make_encoder as c_make_encoder
[9] Fix | Delete
except ImportError:
[10] Fix | Delete
c_make_encoder = None
[11] Fix | Delete
[12] Fix | Delete
ESCAPE = re.compile(r'[\x00-\x1f\\"\b\f\n\r\t]')
[13] Fix | Delete
ESCAPE_ASCII = re.compile(r'([\\"]|[^\ -~])')
[14] Fix | Delete
HAS_UTF8 = re.compile(r'[\x80-\xff]')
[15] Fix | Delete
ESCAPE_DCT = {
[16] Fix | Delete
'\\': '\\\\',
[17] Fix | Delete
'"': '\\"',
[18] Fix | Delete
'\b': '\\b',
[19] Fix | Delete
'\f': '\\f',
[20] Fix | Delete
'\n': '\\n',
[21] Fix | Delete
'\r': '\\r',
[22] Fix | Delete
'\t': '\\t',
[23] Fix | Delete
}
[24] Fix | Delete
for i in range(0x20):
[25] Fix | Delete
ESCAPE_DCT.setdefault(chr(i), '\\u{0:04x}'.format(i))
[26] Fix | Delete
#ESCAPE_DCT.setdefault(chr(i), '\\u%04x' % (i,))
[27] Fix | Delete
[28] Fix | Delete
INFINITY = float('inf')
[29] Fix | Delete
FLOAT_REPR = float.__repr__
[30] Fix | Delete
[31] Fix | Delete
def encode_basestring(s):
[32] Fix | Delete
"""Return a JSON representation of a Python string
[33] Fix | Delete
[34] Fix | Delete
"""
[35] Fix | Delete
def replace(match):
[36] Fix | Delete
return ESCAPE_DCT[match.group(0)]
[37] Fix | Delete
return '"' + ESCAPE.sub(replace, s) + '"'
[38] Fix | Delete
[39] Fix | Delete
[40] Fix | Delete
def py_encode_basestring_ascii(s):
[41] Fix | Delete
"""Return an ASCII-only JSON representation of a Python string
[42] Fix | Delete
[43] Fix | Delete
"""
[44] Fix | Delete
if isinstance(s, str) and HAS_UTF8.search(s) is not None:
[45] Fix | Delete
s = s.decode('utf-8')
[46] Fix | Delete
def replace(match):
[47] Fix | Delete
s = match.group(0)
[48] Fix | Delete
try:
[49] Fix | Delete
return ESCAPE_DCT[s]
[50] Fix | Delete
except KeyError:
[51] Fix | Delete
n = ord(s)
[52] Fix | Delete
if n < 0x10000:
[53] Fix | Delete
return '\\u{0:04x}'.format(n)
[54] Fix | Delete
#return '\\u%04x' % (n,)
[55] Fix | Delete
else:
[56] Fix | Delete
# surrogate pair
[57] Fix | Delete
n -= 0x10000
[58] Fix | Delete
s1 = 0xd800 | ((n >> 10) & 0x3ff)
[59] Fix | Delete
s2 = 0xdc00 | (n & 0x3ff)
[60] Fix | Delete
return '\\u{0:04x}\\u{1:04x}'.format(s1, s2)
[61] Fix | Delete
#return '\\u%04x\\u%04x' % (s1, s2)
[62] Fix | Delete
return '"' + str(ESCAPE_ASCII.sub(replace, s)) + '"'
[63] Fix | Delete
[64] Fix | Delete
[65] Fix | Delete
encode_basestring_ascii = (
[66] Fix | Delete
c_encode_basestring_ascii or py_encode_basestring_ascii)
[67] Fix | Delete
[68] Fix | Delete
class JSONEncoder(object):
[69] Fix | Delete
"""Extensible JSON <http://json.org> encoder for Python data structures.
[70] Fix | Delete
[71] Fix | Delete
Supports the following objects and types by default:
[72] Fix | Delete
[73] Fix | Delete
+-------------------+---------------+
[74] Fix | Delete
| Python | JSON |
[75] Fix | Delete
+===================+===============+
[76] Fix | Delete
| dict | object |
[77] Fix | Delete
+-------------------+---------------+
[78] Fix | Delete
| list, tuple | array |
[79] Fix | Delete
+-------------------+---------------+
[80] Fix | Delete
| str, unicode | string |
[81] Fix | Delete
+-------------------+---------------+
[82] Fix | Delete
| int, long, float | number |
[83] Fix | Delete
+-------------------+---------------+
[84] Fix | Delete
| True | true |
[85] Fix | Delete
+-------------------+---------------+
[86] Fix | Delete
| False | false |
[87] Fix | Delete
+-------------------+---------------+
[88] Fix | Delete
| None | null |
[89] Fix | Delete
+-------------------+---------------+
[90] Fix | Delete
[91] Fix | Delete
To extend this to recognize other objects, subclass and implement a
[92] Fix | Delete
``.default()`` method with another method that returns a serializable
[93] Fix | Delete
object for ``o`` if possible, otherwise it should call the superclass
[94] Fix | Delete
implementation (to raise ``TypeError``).
[95] Fix | Delete
[96] Fix | Delete
"""
[97] Fix | Delete
item_separator = ', '
[98] Fix | Delete
key_separator = ': '
[99] Fix | Delete
def __init__(self, skipkeys=False, ensure_ascii=True,
[100] Fix | Delete
check_circular=True, allow_nan=True, sort_keys=False,
[101] Fix | Delete
indent=None, separators=None, encoding='utf-8', default=None):
[102] Fix | Delete
"""Constructor for JSONEncoder, with sensible defaults.
[103] Fix | Delete
[104] Fix | Delete
If skipkeys is false, then it is a TypeError to attempt
[105] Fix | Delete
encoding of keys that are not str, int, long, float or None. If
[106] Fix | Delete
skipkeys is True, such items are simply skipped.
[107] Fix | Delete
[108] Fix | Delete
If *ensure_ascii* is true (the default), all non-ASCII
[109] Fix | Delete
characters in the output are escaped with \uXXXX sequences,
[110] Fix | Delete
and the results are str instances consisting of ASCII
[111] Fix | Delete
characters only. If ensure_ascii is False, a result may be a
[112] Fix | Delete
unicode instance. This usually happens if the input contains
[113] Fix | Delete
unicode strings or the *encoding* parameter is used.
[114] Fix | Delete
[115] Fix | Delete
If check_circular is true, then lists, dicts, and custom encoded
[116] Fix | Delete
objects will be checked for circular references during encoding to
[117] Fix | Delete
prevent an infinite recursion (which would cause an OverflowError).
[118] Fix | Delete
Otherwise, no such check takes place.
[119] Fix | Delete
[120] Fix | Delete
If allow_nan is true, then NaN, Infinity, and -Infinity will be
[121] Fix | Delete
encoded as such. This behavior is not JSON specification compliant,
[122] Fix | Delete
but is consistent with most JavaScript based encoders and decoders.
[123] Fix | Delete
Otherwise, it will be a ValueError to encode such floats.
[124] Fix | Delete
[125] Fix | Delete
If sort_keys is true, then the output of dictionaries will be
[126] Fix | Delete
sorted by key; this is useful for regression tests to ensure
[127] Fix | Delete
that JSON serializations can be compared on a day-to-day basis.
[128] Fix | Delete
[129] Fix | Delete
If indent is a non-negative integer, then JSON array
[130] Fix | Delete
elements and object members will be pretty-printed with that
[131] Fix | Delete
indent level. An indent level of 0 will only insert newlines.
[132] Fix | Delete
None is the most compact representation. Since the default
[133] Fix | Delete
item separator is ', ', the output might include trailing
[134] Fix | Delete
whitespace when indent is specified. You can use
[135] Fix | Delete
separators=(',', ': ') to avoid this.
[136] Fix | Delete
[137] Fix | Delete
If specified, separators should be a (item_separator, key_separator)
[138] Fix | Delete
tuple. The default is (', ', ': '). To get the most compact JSON
[139] Fix | Delete
representation you should specify (',', ':') to eliminate whitespace.
[140] Fix | Delete
[141] Fix | Delete
If specified, default is a function that gets called for objects
[142] Fix | Delete
that can't otherwise be serialized. It should return a JSON encodable
[143] Fix | Delete
version of the object or raise a ``TypeError``.
[144] Fix | Delete
[145] Fix | Delete
If encoding is not None, then all input strings will be
[146] Fix | Delete
transformed into unicode using that encoding prior to JSON-encoding.
[147] Fix | Delete
The default is UTF-8.
[148] Fix | Delete
[149] Fix | Delete
"""
[150] Fix | Delete
[151] Fix | Delete
self.skipkeys = skipkeys
[152] Fix | Delete
self.ensure_ascii = ensure_ascii
[153] Fix | Delete
self.check_circular = check_circular
[154] Fix | Delete
self.allow_nan = allow_nan
[155] Fix | Delete
self.sort_keys = sort_keys
[156] Fix | Delete
self.indent = indent
[157] Fix | Delete
if separators is not None:
[158] Fix | Delete
self.item_separator, self.key_separator = separators
[159] Fix | Delete
if default is not None:
[160] Fix | Delete
self.default = default
[161] Fix | Delete
self.encoding = encoding
[162] Fix | Delete
[163] Fix | Delete
def default(self, o):
[164] Fix | Delete
"""Implement this method in a subclass such that it returns
[165] Fix | Delete
a serializable object for ``o``, or calls the base implementation
[166] Fix | Delete
(to raise a ``TypeError``).
[167] Fix | Delete
[168] Fix | Delete
For example, to support arbitrary iterators, you could
[169] Fix | Delete
implement default like this::
[170] Fix | Delete
[171] Fix | Delete
def default(self, o):
[172] Fix | Delete
try:
[173] Fix | Delete
iterable = iter(o)
[174] Fix | Delete
except TypeError:
[175] Fix | Delete
pass
[176] Fix | Delete
else:
[177] Fix | Delete
return list(iterable)
[178] Fix | Delete
# Let the base class default method raise the TypeError
[179] Fix | Delete
return JSONEncoder.default(self, o)
[180] Fix | Delete
[181] Fix | Delete
"""
[182] Fix | Delete
raise TypeError(repr(o) + " is not JSON serializable")
[183] Fix | Delete
[184] Fix | Delete
def encode(self, o):
[185] Fix | Delete
"""Return a JSON string representation of a Python data structure.
[186] Fix | Delete
[187] Fix | Delete
>>> JSONEncoder().encode({"foo": ["bar", "baz"]})
[188] Fix | Delete
'{"foo": ["bar", "baz"]}'
[189] Fix | Delete
[190] Fix | Delete
"""
[191] Fix | Delete
# This is for extremely simple cases and benchmarks.
[192] Fix | Delete
if isinstance(o, basestring):
[193] Fix | Delete
if isinstance(o, str):
[194] Fix | Delete
_encoding = self.encoding
[195] Fix | Delete
if (_encoding is not None
[196] Fix | Delete
and not (_encoding == 'utf-8')):
[197] Fix | Delete
o = o.decode(_encoding)
[198] Fix | Delete
if self.ensure_ascii:
[199] Fix | Delete
return encode_basestring_ascii(o)
[200] Fix | Delete
else:
[201] Fix | Delete
return encode_basestring(o)
[202] Fix | Delete
# This doesn't pass the iterator directly to ''.join() because the
[203] Fix | Delete
# exceptions aren't as detailed. The list call should be roughly
[204] Fix | Delete
# equivalent to the PySequence_Fast that ''.join() would do.
[205] Fix | Delete
chunks = self.iterencode(o, _one_shot=True)
[206] Fix | Delete
if not isinstance(chunks, (list, tuple)):
[207] Fix | Delete
chunks = list(chunks)
[208] Fix | Delete
return ''.join(chunks)
[209] Fix | Delete
[210] Fix | Delete
def iterencode(self, o, _one_shot=False):
[211] Fix | Delete
"""Encode the given object and yield each string
[212] Fix | Delete
representation as available.
[213] Fix | Delete
[214] Fix | Delete
For example::
[215] Fix | Delete
[216] Fix | Delete
for chunk in JSONEncoder().iterencode(bigobject):
[217] Fix | Delete
mysocket.write(chunk)
[218] Fix | Delete
[219] Fix | Delete
"""
[220] Fix | Delete
if self.check_circular:
[221] Fix | Delete
markers = {}
[222] Fix | Delete
else:
[223] Fix | Delete
markers = None
[224] Fix | Delete
if self.ensure_ascii:
[225] Fix | Delete
_encoder = encode_basestring_ascii
[226] Fix | Delete
else:
[227] Fix | Delete
_encoder = encode_basestring
[228] Fix | Delete
if self.encoding != 'utf-8':
[229] Fix | Delete
def _encoder(o, _orig_encoder=_encoder, _encoding=self.encoding):
[230] Fix | Delete
if isinstance(o, str):
[231] Fix | Delete
o = o.decode(_encoding)
[232] Fix | Delete
return _orig_encoder(o)
[233] Fix | Delete
[234] Fix | Delete
def floatstr(o, allow_nan=self.allow_nan,
[235] Fix | Delete
_repr=FLOAT_REPR, _inf=INFINITY, _neginf=-INFINITY):
[236] Fix | Delete
# Check for specials. Note that this type of test is processor
[237] Fix | Delete
# and/or platform-specific, so do tests which don't depend on the
[238] Fix | Delete
# internals.
[239] Fix | Delete
[240] Fix | Delete
if o != o:
[241] Fix | Delete
text = 'NaN'
[242] Fix | Delete
elif o == _inf:
[243] Fix | Delete
text = 'Infinity'
[244] Fix | Delete
elif o == _neginf:
[245] Fix | Delete
text = '-Infinity'
[246] Fix | Delete
else:
[247] Fix | Delete
return _repr(o)
[248] Fix | Delete
[249] Fix | Delete
if not allow_nan:
[250] Fix | Delete
raise ValueError(
[251] Fix | Delete
"Out of range float values are not JSON compliant: " +
[252] Fix | Delete
repr(o))
[253] Fix | Delete
[254] Fix | Delete
return text
[255] Fix | Delete
[256] Fix | Delete
[257] Fix | Delete
if (_one_shot and c_make_encoder is not None
[258] Fix | Delete
and self.indent is None and not self.sort_keys):
[259] Fix | Delete
_iterencode = c_make_encoder(
[260] Fix | Delete
markers, self.default, _encoder, self.indent,
[261] Fix | Delete
self.key_separator, self.item_separator, self.sort_keys,
[262] Fix | Delete
self.skipkeys, self.allow_nan)
[263] Fix | Delete
else:
[264] Fix | Delete
_iterencode = _make_iterencode(
[265] Fix | Delete
markers, self.default, _encoder, self.indent, floatstr,
[266] Fix | Delete
self.key_separator, self.item_separator, self.sort_keys,
[267] Fix | Delete
self.skipkeys, _one_shot)
[268] Fix | Delete
return _iterencode(o, 0)
[269] Fix | Delete
[270] Fix | Delete
def _make_iterencode(markers, _default, _encoder, _indent, _floatstr,
[271] Fix | Delete
_key_separator, _item_separator, _sort_keys, _skipkeys, _one_shot,
[272] Fix | Delete
## HACK: hand-optimized bytecode; turn globals into locals
[273] Fix | Delete
ValueError=ValueError,
[274] Fix | Delete
basestring=basestring,
[275] Fix | Delete
dict=dict,
[276] Fix | Delete
float=float,
[277] Fix | Delete
id=id,
[278] Fix | Delete
int=int,
[279] Fix | Delete
isinstance=isinstance,
[280] Fix | Delete
list=list,
[281] Fix | Delete
long=long,
[282] Fix | Delete
str=str,
[283] Fix | Delete
tuple=tuple,
[284] Fix | Delete
):
[285] Fix | Delete
[286] Fix | Delete
def _iterencode_list(lst, _current_indent_level):
[287] Fix | Delete
if not lst:
[288] Fix | Delete
yield '[]'
[289] Fix | Delete
return
[290] Fix | Delete
if markers is not None:
[291] Fix | Delete
markerid = id(lst)
[292] Fix | Delete
if markerid in markers:
[293] Fix | Delete
raise ValueError("Circular reference detected")
[294] Fix | Delete
markers[markerid] = lst
[295] Fix | Delete
buf = '['
[296] Fix | Delete
if _indent is not None:
[297] Fix | Delete
_current_indent_level += 1
[298] Fix | Delete
newline_indent = '\n' + (' ' * (_indent * _current_indent_level))
[299] Fix | Delete
separator = _item_separator + newline_indent
[300] Fix | Delete
buf += newline_indent
[301] Fix | Delete
else:
[302] Fix | Delete
newline_indent = None
[303] Fix | Delete
separator = _item_separator
[304] Fix | Delete
first = True
[305] Fix | Delete
for value in lst:
[306] Fix | Delete
if first:
[307] Fix | Delete
first = False
[308] Fix | Delete
else:
[309] Fix | Delete
buf = separator
[310] Fix | Delete
if isinstance(value, basestring):
[311] Fix | Delete
yield buf + _encoder(value)
[312] Fix | Delete
elif value is None:
[313] Fix | Delete
yield buf + 'null'
[314] Fix | Delete
elif value is True:
[315] Fix | Delete
yield buf + 'true'
[316] Fix | Delete
elif value is False:
[317] Fix | Delete
yield buf + 'false'
[318] Fix | Delete
elif isinstance(value, (int, long)):
[319] Fix | Delete
yield buf + str(value)
[320] Fix | Delete
elif isinstance(value, float):
[321] Fix | Delete
yield buf + _floatstr(value)
[322] Fix | Delete
else:
[323] Fix | Delete
yield buf
[324] Fix | Delete
if isinstance(value, (list, tuple)):
[325] Fix | Delete
chunks = _iterencode_list(value, _current_indent_level)
[326] Fix | Delete
elif isinstance(value, dict):
[327] Fix | Delete
chunks = _iterencode_dict(value, _current_indent_level)
[328] Fix | Delete
else:
[329] Fix | Delete
chunks = _iterencode(value, _current_indent_level)
[330] Fix | Delete
for chunk in chunks:
[331] Fix | Delete
yield chunk
[332] Fix | Delete
if newline_indent is not None:
[333] Fix | Delete
_current_indent_level -= 1
[334] Fix | Delete
yield '\n' + (' ' * (_indent * _current_indent_level))
[335] Fix | Delete
yield ']'
[336] Fix | Delete
if markers is not None:
[337] Fix | Delete
del markers[markerid]
[338] Fix | Delete
[339] Fix | Delete
def _iterencode_dict(dct, _current_indent_level):
[340] Fix | Delete
if not dct:
[341] Fix | Delete
yield '{}'
[342] Fix | Delete
return
[343] Fix | Delete
if markers is not None:
[344] Fix | Delete
markerid = id(dct)
[345] Fix | Delete
if markerid in markers:
[346] Fix | Delete
raise ValueError("Circular reference detected")
[347] Fix | Delete
markers[markerid] = dct
[348] Fix | Delete
yield '{'
[349] Fix | Delete
if _indent is not None:
[350] Fix | Delete
_current_indent_level += 1
[351] Fix | Delete
newline_indent = '\n' + (' ' * (_indent * _current_indent_level))
[352] Fix | Delete
item_separator = _item_separator + newline_indent
[353] Fix | Delete
yield newline_indent
[354] Fix | Delete
else:
[355] Fix | Delete
newline_indent = None
[356] Fix | Delete
item_separator = _item_separator
[357] Fix | Delete
first = True
[358] Fix | Delete
if _sort_keys:
[359] Fix | Delete
items = sorted(dct.items(), key=lambda kv: kv[0])
[360] Fix | Delete
else:
[361] Fix | Delete
items = dct.iteritems()
[362] Fix | Delete
for key, value in items:
[363] Fix | Delete
if isinstance(key, basestring):
[364] Fix | Delete
pass
[365] Fix | Delete
# JavaScript is weakly typed for these, so it makes sense to
[366] Fix | Delete
# also allow them. Many encoders seem to do something like this.
[367] Fix | Delete
elif isinstance(key, float):
[368] Fix | Delete
key = _floatstr(key)
[369] Fix | Delete
elif key is True:
[370] Fix | Delete
key = 'true'
[371] Fix | Delete
elif key is False:
[372] Fix | Delete
key = 'false'
[373] Fix | Delete
elif key is None:
[374] Fix | Delete
key = 'null'
[375] Fix | Delete
elif isinstance(key, (int, long)):
[376] Fix | Delete
key = str(key)
[377] Fix | Delete
elif _skipkeys:
[378] Fix | Delete
continue
[379] Fix | Delete
else:
[380] Fix | Delete
raise TypeError("key " + repr(key) + " is not a string")
[381] Fix | Delete
if first:
[382] Fix | Delete
first = False
[383] Fix | Delete
else:
[384] Fix | Delete
yield item_separator
[385] Fix | Delete
yield _encoder(key)
[386] Fix | Delete
yield _key_separator
[387] Fix | Delete
if isinstance(value, basestring):
[388] Fix | Delete
yield _encoder(value)
[389] Fix | Delete
elif value is None:
[390] Fix | Delete
yield 'null'
[391] Fix | Delete
elif value is True:
[392] Fix | Delete
yield 'true'
[393] Fix | Delete
elif value is False:
[394] Fix | Delete
yield 'false'
[395] Fix | Delete
elif isinstance(value, (int, long)):
[396] Fix | Delete
yield str(value)
[397] Fix | Delete
elif isinstance(value, float):
[398] Fix | Delete
yield _floatstr(value)
[399] Fix | Delete
else:
[400] Fix | Delete
if isinstance(value, (list, tuple)):
[401] Fix | Delete
chunks = _iterencode_list(value, _current_indent_level)
[402] Fix | Delete
elif isinstance(value, dict):
[403] Fix | Delete
chunks = _iterencode_dict(value, _current_indent_level)
[404] Fix | Delete
else:
[405] Fix | Delete
chunks = _iterencode(value, _current_indent_level)
[406] Fix | Delete
for chunk in chunks:
[407] Fix | Delete
yield chunk
[408] Fix | Delete
if newline_indent is not None:
[409] Fix | Delete
_current_indent_level -= 1
[410] Fix | Delete
yield '\n' + (' ' * (_indent * _current_indent_level))
[411] Fix | Delete
yield '}'
[412] Fix | Delete
if markers is not None:
[413] Fix | Delete
del markers[markerid]
[414] Fix | Delete
[415] Fix | Delete
def _iterencode(o, _current_indent_level):
[416] Fix | Delete
if isinstance(o, basestring):
[417] Fix | Delete
yield _encoder(o)
[418] Fix | Delete
elif o is None:
[419] Fix | Delete
yield 'null'
[420] Fix | Delete
elif o is True:
[421] Fix | Delete
yield 'true'
[422] Fix | Delete
elif o is False:
[423] Fix | Delete
yield 'false'
[424] Fix | Delete
elif isinstance(o, (int, long)):
[425] Fix | Delete
yield str(o)
[426] Fix | Delete
elif isinstance(o, float):
[427] Fix | Delete
yield _floatstr(o)
[428] Fix | Delete
elif isinstance(o, (list, tuple)):
[429] Fix | Delete
for chunk in _iterencode_list(o, _current_indent_level):
[430] Fix | Delete
yield chunk
[431] Fix | Delete
elif isinstance(o, dict):
[432] Fix | Delete
for chunk in _iterencode_dict(o, _current_indent_level):
[433] Fix | Delete
yield chunk
[434] Fix | Delete
else:
[435] Fix | Delete
if markers is not None:
[436] Fix | Delete
markerid = id(o)
[437] Fix | Delete
if markerid in markers:
[438] Fix | Delete
raise ValueError("Circular reference detected")
[439] Fix | Delete
markers[markerid] = o
[440] Fix | Delete
o = _default(o)
[441] Fix | Delete
for chunk in _iterencode(o, _current_indent_level):
[442] Fix | Delete
yield chunk
[443] Fix | Delete
if markers is not None:
[444] Fix | Delete
del markers[markerid]
[445] Fix | Delete
[446] Fix | Delete
return _iterencode
[447] Fix | Delete
[448] Fix | Delete
It is recommended that you Edit text format, this type of Fix handles quite a lot in one request
Function