What is the difference between json.dump() and json.dumps() in python?

前端 未结 4 1169
遥遥无期
遥遥无期 2020-12-04 08:15

I searched in this official document to find difference between the json.dump() and json.dumps() in python. It is clear that they are related with file write option.
But

4条回答
  •  失恋的感觉
    2020-12-04 08:39

    One notable difference in Python 2 is that if you're using ensure_ascii=False, dump will properly write UTF-8 encoded data into the file (unless you used 8-bit strings with extended characters that are not UTF-8):

    dumps on the other hand, with ensure_ascii=False can produce a str or unicode just depending on what types you used for strings:

    Serialize obj to a JSON formatted str using this conversion table. If ensure_ascii is False, the result may contain non-ASCII characters and the return value may be a unicode instance.

    (emphasis mine). Note that it may still be a str instance as well.

    Thus you cannot use its return value to save the structure into file without checking which format was returned and possibly playing with unicode.encode.

    This of course is not valid concern in Python 3 any more, since there is no more this 8-bit/Unicode confusion.


    As for load vs loads, load considers the whole file to be one JSON document, so you cannot use it to read multiple newline limited JSON documents from a single file.

提交回复
热议问题