[docs]classJSONEncoder(object):"""Extensible JSON <http://json.org> encoder for Python data structures. Supports the following objects and types by default: +-------------------+---------------+ | Python | JSON | +===================+===============+ | dict | object | +-------------------+---------------+ | list, tuple | array | +-------------------+---------------+ | str | string | +-------------------+---------------+ | int, float | number | +-------------------+---------------+ | True | true | +-------------------+---------------+ | False | false | +-------------------+---------------+ | None | null | +-------------------+---------------+ To extend this to recognize other objects, subclass and implement a ``.default()`` method with another method that returns a serializable object for ``o`` if possible, otherwise it should call the superclass implementation (to raise ``TypeError``). """item_separator=', 'key_separator=': 'def__init__(self,*,skipkeys=False,ensure_ascii=True,check_circular=True,allow_nan=True,sort_keys=False,indent=None,separators=None,default=None):"""Constructor for JSONEncoder, with sensible defaults. If skipkeys is false, then it is a TypeError to attempt encoding of keys that are not str, int, float or None. If skipkeys is True, such items are simply skipped. If ensure_ascii is true, the output is guaranteed to be str objects with all incoming non-ASCII characters escaped. If ensure_ascii is false, the output can contain non-ASCII characters. If check_circular is true, then lists, dicts, and custom encoded objects will be checked for circular references during encoding to prevent an infinite recursion (which would cause an OverflowError). Otherwise, no such check takes place. If allow_nan is true, then NaN, Infinity, and -Infinity will be encoded as such. This behavior is not JSON specification compliant, but is consistent with most JavaScript based encoders and decoders. Otherwise, it will be a ValueError to encode such floats. If sort_keys is true, then the output of dictionaries will be sorted by key; this is useful for regression tests to ensure that JSON serializations can be compared on a day-to-day basis. If indent is a non-negative integer, then JSON array elements and object members will be pretty-printed with that indent level. An indent level of 0 will only insert newlines. None is the most compact representation. If specified, separators should be an (item_separator, key_separator) tuple. The default is (', ', ': ') if *indent* is ``None`` and (',', ': ') otherwise. To get the most compact JSON representation, you should specify (',', ':') to eliminate whitespace. If specified, default is a function that gets called for objects that can't otherwise be serialized. It should return a JSON encodable version of the object or raise a ``TypeError``. """self.skipkeys=skipkeysself.ensure_ascii=ensure_asciiself.check_circular=check_circularself.allow_nan=allow_nanself.sort_keys=sort_keysself.indent=indentifseparatorsisnotNone:self.item_separator,self.key_separator=separatorselifindentisnotNone:self.item_separator=','ifdefaultisnotNone:self.default=default

[docs]defdefault(self,o):"""Implement this method in a subclass such that it returns a serializable object for ``o``, or calls the base implementation (to raise a ``TypeError``). For example, to support arbitrary iterators, you could implement default like this:: def default(self, o): try: iterable = iter(o) except TypeError: pass else: return list(iterable) # Let the base class default method raise the TypeError return JSONEncoder.default(self, o) """raiseTypeError("Object of type '%s' is not JSON serializable"%o.__class__.__name__)

[docs]defencode(self,o):"""Return a JSON string representation of a Python data structure. >>> from json.encoder import JSONEncoder >>> JSONEncoder().encode({"foo": ["bar", "baz"]}) '{"foo": ["bar", "baz"]}' """# This is for extremely simple cases and benchmarks.ifisinstance(o,str):ifself.ensure_ascii:returnencode_basestring_ascii(o)else:returnencode_basestring(o)# This doesn't pass the iterator directly to ''.join() because the# exceptions aren't as detailed. The list call should be roughly# equivalent to the PySequence_Fast that ''.join() would do.chunks=self.iterencode(o,_one_shot=True)ifnotisinstance(chunks,(list,tuple)):chunks=list(chunks)return''.join(chunks)

[docs]defiterencode(self,o,_one_shot=False):"""Encode the given object and yield each string representation as available. For example:: for chunk in JSONEncoder().iterencode(bigobject): mysocket.write(chunk) """ifself.check_circular:markers={}else:markers=Noneifself.ensure_ascii:_encoder=encode_basestring_asciielse:_encoder=encode_basestringdeffloatstr(o,allow_nan=self.allow_nan,_repr=float.__repr__,_inf=INFINITY,_neginf=-INFINITY):# Check for specials. Note that this type of test is processor# and/or platform-specific, so do tests which don't depend on the# internals.ifo!=o:text='NaN'elifo==_inf:text='Infinity'elifo==_neginf:text='-Infinity'else:return_repr(o)ifnotallow_nan:raiseValueError("Out of range float values are not JSON compliant: "+repr(o))returntextif(_one_shotandc_make_encoderisnotNoneandself.indentisNone):_iterencode=c_make_encoder(markers,self.default,_encoder,self.indent,self.key_separator,self.item_separator,self.sort_keys,self.skipkeys,self.allow_nan)else:_iterencode=_make_iterencode(markers,self.default,_encoder,self.indent,floatstr,self.key_separator,self.item_separator,self.sort_keys,self.skipkeys,_one_shot)return_iterencode(o,0)

def_make_iterencode(markers,_default,_encoder,_indent,_floatstr,_key_separator,_item_separator,_sort_keys,_skipkeys,_one_shot,## HACK: hand-optimized bytecode; turn globals into localsValueError=ValueError,dict=dict,float=float,id=id,int=int,isinstance=isinstance,list=list,str=str,tuple=tuple,_intstr=int.__str__,):if_indentisnotNoneandnotisinstance(_indent,str):_indent=' '*_indentdef_iterencode_list(lst,_current_indent_level):ifnotlst:yield'[]'returnifmarkersisnotNone:markerid=id(lst)ifmarkeridinmarkers:raiseValueError("Circular reference detected")markers[markerid]=lstbuf='['if_indentisnotNone:_current_indent_level+=1newline_indent='\n'+_indent*_current_indent_levelseparator=_item_separator+newline_indentbuf+=newline_indentelse:newline_indent=Noneseparator=_item_separatorfirst=Trueforvalueinlst:iffirst:first=Falseelse:buf=separatorifisinstance(value,str):yieldbuf+_encoder(value)elifvalueisNone:yieldbuf+'null'elifvalueisTrue:yieldbuf+'true'elifvalueisFalse:yieldbuf+'false'elifisinstance(value,int):# Subclasses of int/float may override __str__, but we still# want to encode them as integers/floats in JSON. One example# within the standard library is IntEnum.yieldbuf+_intstr(value)elifisinstance(value,float):# see comment above for intyieldbuf+_floatstr(value)else:yieldbufifisinstance(value,(list,tuple)):chunks=_iterencode_list(value,_current_indent_level)elifisinstance(value,dict):chunks=_iterencode_dict(value,_current_indent_level)else:chunks=_iterencode(value,_current_indent_level)yield fromchunksifnewline_indentisnotNone:_current_indent_level-=1yield'\n'+_indent*_current_indent_levelyield']'ifmarkersisnotNone:delmarkers[markerid]def_iterencode_dict(dct,_current_indent_level):ifnotdct:yield'{}'returnifmarkersisnotNone:markerid=id(dct)ifmarkeridinmarkers:raiseValueError("Circular reference detected")markers[markerid]=dctyield'{'if_indentisnotNone:_current_indent_level+=1newline_indent='\n'+_indent*_current_indent_levelitem_separator=_item_separator+newline_indentyieldnewline_indentelse:newline_indent=Noneitem_separator=_item_separatorfirst=Trueif_sort_keys:items=sorted(dct.items(),key=lambdakv:kv[0])else:items=dct.items()forkey,valueinitems:ifisinstance(key,str):pass# JavaScript is weakly typed for these, so it makes sense to# also allow them. Many encoders seem to do something like this.elifisinstance(key,float):# see comment for int/float in _make_iterencodekey=_floatstr(key)elifkeyisTrue:key='true'elifkeyisFalse:key='false'elifkeyisNone:key='null'elifisinstance(key,int):# see comment for int/float in _make_iterencodekey=_intstr(key)elif_skipkeys:continueelse:raiseTypeError("key "+repr(key)+" is not a string")iffirst:first=Falseelse:yielditem_separatoryield_encoder(key)yield_key_separatorifisinstance(value,str):yield_encoder(value)elifvalueisNone:yield'null'elifvalueisTrue:yield'true'elifvalueisFalse:yield'false'elifisinstance(value,int):# see comment for int/float in _make_iterencodeyield_intstr(value)elifisinstance(value,float):# see comment for int/float in _make_iterencodeyield_floatstr(value)else:ifisinstance(value,(list,tuple)):chunks=_iterencode_list(value,_current_indent_level)elifisinstance(value,dict):chunks=_iterencode_dict(value,_current_indent_level)else:chunks=_iterencode(value,_current_indent_level)yield fromchunksifnewline_indentisnotNone:_current_indent_level-=1yield'\n'+_indent*_current_indent_levelyield'}'ifmarkersisnotNone:delmarkers[markerid]def_iterencode(o,_current_indent_level):ifisinstance(o,str):yield_encoder(o)elifoisNone:yield'null'elifoisTrue:yield'true'elifoisFalse:yield'false'elifisinstance(o,int):# see comment for int/float in _make_iterencodeyield_intstr(o)elifisinstance(o,float):# see comment for int/float in _make_iterencodeyield_floatstr(o)elifisinstance(o,(list,tuple)):yield from_iterencode_list(o,_current_indent_level)elifisinstance(o,dict):yield from_iterencode_dict(o,_current_indent_level)else:ifmarkersisnotNone:markerid=id(o)ifmarkeridinmarkers:raiseValueError("Circular reference detected")markers[markerid]=oo=_default(o)yield from_iterencode(o,_current_indent_level)ifmarkersisnotNone:delmarkers[markerid]return_iterencode