python - python中的json.dump()和json.dumps()有什么区别?

我在 this 中搜索过官方文档查找python中 json.dump() 和 json.dumps() 之间的区别。很明显,它们与文件写入选项有关。
但是它们之间的详细区别是什么?在什么情况下一个比另一个更有优势?

最佳答案

除了文档说的内容之外,没有其他要添加的内容。如果您想将 JSON 转储到文件/套接字或其他任何内容中,那么您应该使用 dump()。如果您只需要它作为字符串(用于打印、解析或其他),请使用 dumps() (dump string)

如 Antti Haapala in this answer 所述, ensure_ascii 行为有一些细微差别。这主要是由于底层 write() 函数是如何工作的,因为它对 block 而不是整个字符串进行操作。查看他的答案以获取更多详细信息。

json.dump()

Serialize obj as a JSON formatted stream to fp (a .write()-supporting file-like object

If ensure_ascii is False, some chunks written to fp may be unicode instances

json.dumps()

Serialize obj to a JSON formatted str

If ensure_ascii is False, the result may contain non-ASCII characters and the return value may be a unicode instance

https://stackoverflow.com/questions/36059194/

相关文章:

json - json.js 和 json2.js 的区别

javascript - 将 JSON 发送到服务器并返回 JSON,无需 JQuery

javascript - 如果名称包含点,如何获取对象值?

python - 如何使用 python 请求和处理 JSON?

javascript - 在 promise 链上使用 setTimeout

c# - 将 POST 中的 json 发送到 Web API 服务时出错

python - Google App Engine 模型的 JSON 序列化

javascript - 请求的资源错误中不存在 'Access-Control-Allow-Ori

javascript - JSON Stringify 因 UTC 而更改日期时间

javascript - JSON 是否应该包含空值