What is the difference between json.load() and json.loads() functions

前端 未结 6 772
天涯浪人
天涯浪人 2020-11-29 16:36

In Python, what is the difference between json.load() and json.loads()?

I guess that the load() function must be used with a file

6条回答
  •  醉话见心
    2020-11-29 16:44

    In python3.7.7, the definition of json.load is as below according to cpython source code:

    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)
    

    json.load actually calls json.loads and use fp.read() as the first argument.

    So if your code is:

    with open (file) as fp:
        s = fp.read()
        json.loads(s)
    

    It's the same to do this:

    with open (file) as fp:
        json.load(fp)
    

    But if you need to specify the bytes reading from the file as like fp.read(10) or the string/bytes you want to deserialize is not from file, you should use json.loads()

    As for json.loads(), it not only deserialize string but also bytes. If s is bytes or bytearray, it will be decoded to string first. You can also find it in the source code.

    def loads(s, *, encoding=None, cls=None, object_hook=None, parse_float=None,
            parse_int=None, parse_constant=None, object_pairs_hook=None, **kw):
        """Deserialize ``s`` (a ``str``, ``bytes`` or ``bytearray`` instance
        containing a JSON document) to a Python object.
    
        ...
    
        """
        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')
    
    

提交回复
热议问题