python中的json.dump()和json.dumps()有什么区别? [英] What is the difference between json.dump() and json.dumps() in python?

查看:610
本文介绍了python中的json.dump()和json.dumps()有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在官方文档中进行了搜索,以找出json.dump之间的区别()和python中的json.dumps().显然,它们与文件写入选项有关.
但是它们之间的详细区别是什么?在什么情况下,一个比另一个具有更多的优势?

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 what is the detailed difference between them and in what situations one has more advantage than other?

推荐答案

除了文档所说的以外,没有什么可添加的.如果要将JSON转储到文件/套接字或其他文件中,则应使用dump().如果只需要它作为字符串(用于打印,解析或其他操作),则使用dumps()(转储字符串)

There isn't pretty much anything else to add other than what the docs say. If you want to dump the JSON into a file/socket or whatever, then you should go for dump(). If you only need it as a string (for printing, parsing or whatever) then use dumps() (dump string)

Antii Haapala在此答案中所述,在ensure_ascii行为上有一些细微的差异.这主要是由于基础write()函数是如何工作的,因为它是按块而不是整个字符串进行操作的.查看答案以获取更多详细信息.

As mentioned by Antii Haapala in this answer, there are some minor differences on the ensure_ascii behaviour. This is mostly due to how the underlying write() function works, being that it operates into chunks rather than the whole string. Check the answer for more details on that.

json.dump()

将obj序列化为JSON格式的流到fp(支持.write()的类似文件的对象

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

如果sure_ascii为False,则写入fp的某些块可能是unicode实例

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

json.dumps()

将obj序列化为JSON格式的str

Serialize obj to a JSON formatted str

如果sure_ascii为False,则结果可能包含非ASCII字符,并且返回值可能是unicode实例

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

这篇关于python中的json.dump()和json.dumps()有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆