version 2 0 9 all dump dumps load loads jsondecoder jsondecodeerror jsonencoder bob ippolito bobredivi com from decoder import jsondecoder jsondecodeerror from encoder import jsonencoder import codecs defaultencoder jsonencoder skipkeysfalse ensureasciitrue checkcirculartrue allownantrue indentnone separatorsnone defaultnone def dumpobj fp skipkeysfalse ensureasciitrue checkcirculartrue allownantrue clsnone indentnone separatorsnone defaultnone sortkeysfalse kw cached encoder if not skipkeys and ensureascii and checkcircular and allownan and cls is none and indent is none and separators is none and default is none and not sortkeys and not kw iterable defaultencoder iterencodeobj else if cls is none cls jsonencoder iterable clsskipkeysskipkeys ensureasciiensureascii checkcircularcheckcircular allownanallownan indentindent separatorsseparators defaultdefault sortkeyssortkeys kw iterencodeobj could accelerate with writelines in some versions of python at a debuggability cost for chunk in iterable fp writechunk def dumpsobj skipkeysfalse ensureasciitrue checkcirculartrue allownantrue clsnone indentnone separatorsnone defaultnone sortkeysfalse kw cached encoder if not skipkeys and ensureascii and checkcircular and allownan and cls is none and indent is none and separators is none and default is none and not sortkeys and not kw return defaultencoder encodeobj if cls is none cls jsonencoder return cls skipkeysskipkeys ensureasciiensureascii checkcircularcheckcircular allownanallownan indentindent separatorsseparators defaultdefault sortkeyssortkeys kw encodeobj defaultdecoder jsondecoderobjecthooknone objectpairshooknone def detectencodingb bstartswith b startswith if bstartswithcodecs bomutf32be codecs bomutf32le return utf32 if bstartswithcodecs bomutf16be codecs bomutf16le return utf16 if bstartswithcodecs bomutf8 return utf8sig if lenb 4 if not b0 00 00 utf32be 00 xx utf16be return utf16be if b1 else utf32be if not b1 xx 00 00 00 utf32le xx 00 00 xx utf16le xx 00 xx utf16le return utf16le if b2 or b3 else utf32le elif lenb 2 if not b0 00 xx utf16be return utf16be if not b1 xx 00 utf16le return utf16le default return utf8 def loadfp clsnone objecthooknone parsefloatnone parseintnone parseconstantnone objectpairshooknone kw return loadsfp read clscls objecthookobjecthook parsefloatparsefloat parseintparseint parseconstantparseconstant objectpairshookobjectpairshook kw def loadss clsnone objecthooknone parsefloatnone parseintnone parseconstantnone objectpairshooknone kw if isinstances str if s startswith ufeff raise jsondecodeerrorunexpected utf8 bom decode using utf8sig s 0 else if not isinstances bytes bytearray raise typeerrorf the json object must be str bytes or bytearray f not s class name s s decodedetectencodings surrogatepass if cls is none and objecthook is none and parseint is none and parsefloat is none and parseconstant is none and objectpairshook is none and not kw return defaultdecoder decodes if cls is none cls jsondecoder if objecthook is not none kw objecthook objecthook if objectpairshook is not none kw objectpairshook objectpairshook if parsefloat is not none kw parsefloat parsefloat if parseint is not none kw parseint parseint if parseconstant is not none kw parseconstant parseconstant return clskw decodes json javascript object notation https json org is a subset of javascript syntax ecma 262 3rd edition used as a lightweight data interchange format mod json exposes an api familiar to users of the standard library mod marshal and mod pickle modules it is derived from a version of the externally maintained simplejson library encoding basic python object hierarchies import json json dumps foo bar baz none 1 0 2 foo bar baz null 1 0 2 print json dumps foo bar foo bar print json dumps u1234 u1234 print json dumps print json dumps c 0 b 0 a 0 sort_keys true a 0 b 0 c 0 from io import stringio io stringio json dump streaming api io io getvalue streaming api compact encoding import json mydict 4 5 6 7 json dumps 1 2 3 mydict separators 1 2 3 4 5 6 7 pretty printing import json print json dumps 4 5 6 7 sort_keys true indent 4 4 5 6 7 decoding json import json obj foo bar baz none 1 0 2 json loads foo bar baz null 1 0 2 obj true json loads foo bar foo x08ar true from io import stringio io stringio streaming api json load io 0 streaming api true specializing json object decoding import json def as_complex dct if __complex__ in dct return complex dct real dct imag return dct json loads __complex__ true real 1 imag 2 object_hook as_complex 1 2j from decimal import decimal json loads 1 1 parse_float decimal decimal 1 1 true specializing json object encoding import json def encode_complex obj if isinstance obj complex return obj real obj imag raise typeerror f object of type obj __class__ __name__ f is not json serializable json dumps 2 1j default encode_complex 2 0 1 0 json jsonencoder default encode_complex encode 2 1j 2 0 1 0 join json jsonencoder default encode_complex iterencode 2 1j 2 0 1 0 using json tool from the shell to validate and pretty print echo json obj python m json tool json obj echo 1 2 3 4 python m json tool expecting property name enclosed in double quotes line 1 column 3 char 2 serialize obj as a json formatted stream to fp a write supporting file like object if skipkeys is true then dict keys that are not basic types str int float bool none will be skipped instead of raising a typeerror if ensure_ascii is false then the strings written to fp can contain non ascii characters if they appear in strings contained in obj otherwise all such characters are escaped in json strings if check_circular is false then the circular reference check for container types will be skipped and a circular reference will result in an recursionerror or worse if allow_nan is false then it will be a valueerror to serialize out of range float values nan inf inf in strict compliance of the json specification instead of using the javascript equivalents nan infinity infinity 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 default obj is a function that should return a serializable version of obj or raise typeerror the default simply raises typeerror if sort_keys is true default false then the output of dictionaries will be sorted by key to use a custom jsonencoder subclass e g one that overrides the default method to serialize additional types specify it with the cls kwarg otherwise jsonencoder is used cached encoder could accelerate with writelines in some versions of python at a debuggability cost serialize obj to a json formatted str if skipkeys is true then dict keys that are not basic types str int float bool none will be skipped instead of raising a typeerror if ensure_ascii is false then the return value can contain non ascii characters if they appear in strings contained in obj otherwise all such characters are escaped in json strings if check_circular is false then the circular reference check for container types will be skipped and a circular reference will result in an recursionerror or worse if allow_nan is false then it will be a valueerror to serialize out of range float values nan inf inf in strict compliance of the json specification instead of using the javascript equivalents nan infinity infinity 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 default obj is a function that should return a serializable version of obj or raise typeerror the default simply raises typeerror if sort_keys is true default false then the output of dictionaries will be sorted by key to use a custom jsonencoder subclass e g one that overrides the default method to serialize additional types specify it with the cls kwarg otherwise jsonencoder is used cached encoder 00 00 utf 32 be 00 xx utf 16 be xx 00 00 00 utf 32 le xx 00 00 xx utf 16 le xx 00 xx utf 16 le 00 xx utf 16 be xx 00 utf 16 le default deserialize fp a read supporting file like object containing a json document to a python object object_hook is an optional function that will be called with the result of any object literal decode a dict the return value of object_hook will be used instead of the dict this feature can be used to implement custom decoders e g json rpc class hinting object_pairs_hook is an optional function that will be called with the result of any object literal decoded with an ordered list of pairs the return value of object_pairs_hook will be used instead of the dict this feature can be used to implement custom decoders if object_hook is also defined the object_pairs_hook takes priority to use a custom jsondecoder subclass specify it with the cls kwarg otherwise jsondecoder is used deserialize s a str bytes or bytearray instance containing a json document to a python object object_hook is an optional function that will be called with the result of any object literal decode a dict the return value of object_hook will be used instead of the dict this feature can be used to implement custom decoders e g json rpc class hinting object_pairs_hook is an optional function that will be called with the result of any object literal decoded with an ordered list of pairs the return value of object_pairs_hook will be used instead of the dict this feature can be used to implement custom decoders if object_hook is also defined the object_pairs_hook takes priority parse_float if specified will be called with the string of every json float to be decoded by default this is equivalent to float num_str this can be used to use another datatype or parser for json floats e g decimal decimal parse_int if specified will be called with the string of every json int to be decoded by default this is equivalent to int num_str this can be used to use another datatype or parser for json integers e g float parse_constant if specified will be called with one of the following strings infinity infinity nan this can be used to raise an exception if invalid json numbers are encountered to use a custom jsondecoder subclass specify it with the cls kwarg otherwise jsondecoder is used
r
__version__ = '2.0.9'
__all__ = [
    'dump', 'dumps', 'load', 'loads',
    'JSONDecoder', 'JSONDecodeError', 'JSONEncoder',
]

__author__ = 'Bob Ippolito <bob@redivi.com>'

from .decoder import JSONDecoder, JSONDecodeError
from .encoder import JSONEncoder
import codecs

_default_encoder = JSONEncoder(
    skipkeys=False,
    ensure_ascii=True,
    check_circular=True,
    allow_nan=True,
    indent=None,
    separators=None,
    default=None,
)

def dump(obj, fp, *, skipkeys=False, ensure_ascii=True, check_circular=True,
        allow_nan=True, cls=None, indent=None, separators=None,
        default=None, sort_keys=False, **kw):
    
    
    if (not skipkeys and ensure_ascii and
        check_circular and allow_nan and
        cls is None and indent is None and separators is None and
        default is None and not sort_keys and not kw):
        iterable = _default_encoder.iterencode(obj)
    else:
        if cls is None:
            cls = JSONEncoder
        iterable = cls(skipkeys=skipkeys, ensure_ascii=ensure_ascii,
            check_circular=check_circular, allow_nan=allow_nan, indent=indent,
            separators=separators,
            default=default, sort_keys=sort_keys, **kw).iterencode(obj)
    
    
    for chunk in iterable:
        fp.write(chunk)


def dumps(obj, *, skipkeys=False, ensure_ascii=True, check_circular=True,
        allow_nan=True, cls=None, indent=None, separators=None,
        default=None, sort_keys=False, **kw):
    
    
    if (not skipkeys and ensure_ascii and
        check_circular and allow_nan and
        cls is None and indent is None and separators is None and
        default is None and not sort_keys and not kw):
        return _default_encoder.encode(obj)
    if cls is None:
        cls = JSONEncoder
    return cls(
        skipkeys=skipkeys, ensure_ascii=ensure_ascii,
        check_circular=check_circular, allow_nan=allow_nan, indent=indent,
        separators=separators, default=default, sort_keys=sort_keys,
        **kw).encode(obj)


_default_decoder = JSONDecoder(object_hook=None, object_pairs_hook=None)


def detect_encoding(b):
    bstartswith = b.startswith
    if bstartswith((codecs.BOM_UTF32_BE, codecs.BOM_UTF32_LE)):
        return 'utf-32'
    if bstartswith((codecs.BOM_UTF16_BE, codecs.BOM_UTF16_LE)):
        return 'utf-16'
    if bstartswith(codecs.BOM_UTF8):
        return 'utf-8-sig'

    if len(b) >= 4:
        if not b[0]:
            
            
            return 'utf-16-be' if b[1] else 'utf-32-be'
        if not b[1]:
            
            
            
            return 'utf-16-le' if b[2] or b[3] else 'utf-32-le'
    elif len(b) == 2:
        if not b[0]:
            
            return 'utf-16-be'
        if not b[1]:
            
            return 'utf-16-le'
    
    return 'utf-8'


def load(fp, *, cls=None, object_hook=None, parse_float=None,
        parse_int=None, parse_constant=None, object_pairs_hook=None, **kw):
    
    return loads(fp.read(),
        cls=cls, object_hook=object_hook,
        parse_float=parse_float, parse_int=parse_int,
        parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)


def loads(s, *, cls=None, object_hook=None, parse_float=None,
        parse_int=None, parse_constant=None, object_pairs_hook=None, **kw):
    
    if isinstance(s, str):
        if s.startswith('\ufeff'):
            raise JSONDecodeError("Unexpected UTF-8 BOM (decode using utf-8-sig)",
                                  s, 0)
    else:
        if not isinstance(s, (bytes, bytearray)):
            raise TypeError(f'the JSON object must be str, bytes or bytearray, '
                            f'not {s.__class__.__name__}')
        s = s.decode(detect_encoding(s), 'surrogatepass')

    if (cls is None and object_hook is None and
            parse_int is None and parse_float is None and
            parse_constant is None and object_pairs_hook is None and not kw):
        return _default_decoder.decode(s)
    if cls is None:
        cls = JSONDecoder
    if object_hook is not None:
        kw['object_hook'] = object_hook
    if object_pairs_hook is not None:
        kw['object_pairs_hook'] = object_pairs_hook
    if parse_float is not None:
        kw['parse_float'] = parse_float
    if parse_int is not None:
        kw['parse_int'] = parse_int
    if parse_constant is not None:
        kw['parse_constant'] = parse_constant
    return cls(**kw).decode(s)