JSON.stringify (Javascript) 和 json.dumps (Python) 在列表中不等价?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46227854/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 17:32:13  来源:igfitidea点击:

JSON.stringify (Javascript) and json.dumps (Python) not equivalent on a list?

javascriptpythonjson

提问by ThePhi

In javascript:

在 JavaScript 中:

var myarray = [2, 3];
var json_myarray = JSON.stringify(myarray) // '[2,3]'

But in Python:

但在 Python 中:

mylist = [2, 3]
json_mylist = json.dumps(mylist) # '[2, 3]' <-- Note the space

So the 2 functions aren't equivalent. It's a bit unexpected for me and a bit problematic when trying to compare some data for example.

所以这两个功能不等价。例如,在尝试比较某些数据时,这对我来说有点出乎意料,并且有点问题。

Some explanation about it?

关于它的一些解释?

回答by Mike Cluck

The difference is that json.dumpsapplies some minor pretty-printing by default but JSON.stringifydoes not.

不同之处在于json.dumps默认情况下会应用一些较小的漂亮打印,但JSON.stringify不会。

To remove all whitespace, like JSON.stringify, you need to specify the separators.

要删除所有空格,例如JSON.stringify,您需要指定分隔符

json_mylist = json.dumps(mylist, separators=(',', ':'))