javascript 与 JSON.stringify() 相比,使用 toString() 有什么区别?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15834172/
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-10-27 02:16:16  来源:igfitidea点击:

What's the difference in using toString() compared to JSON.stringify()?

javascript

提问by user1883212

In both the cases I get in output the content of the object:

在这两种情况下,我都会输出对象的内容:

alert(JSON.stringify(obj));

or

或者

alert(obj.toString());

so... what's the difference? what are the advantages or disadvantages of each one?

所以……有什么区别?每一种的优点或缺点是什么?

Are there practical examples to show the difference?

是否有实际例子来说明差异?

回答by Esailija

Unless you have a custom object with custom .toStringmethod returning JSON.stringifyof that object, there is no objthat would give obj.toString() == JSON.stringify(obj).

除非您有一个带有自定义.toString方法返回JSON.stringify该对象的自定义对象,否则obj不会给obj.toString() == JSON.stringify(obj).

When objis an array like [1,2,3]then .toString()gives:

什么时候obj[1,2,3]then这样的数组.toString()给出:

"1,2,3"

And JSON.stringify:

并且JSON.stringify

"[1,2,3]"

These are close but not quite the same, the JSON serialized one has no ambiguity with commas and directly runs as Javascript or can be parsed as JSON.

这些很接近但不完全相同,JSON序列化的没有逗号歧义,直接作为Javascript运行或可以解析为JSON。

See:

看:

["1,",2,3].toString();
//"1,,2,3" ... so you can't just split by comma and get original array
//it is in fact impossible to restore the original array from this result

JSON.stringify(["1,",2,3])
//'["1,",2,3]'
//original array can be restored exactly

回答by Jacob George

for an object say

对于一个对象说

obj = { a: 'a', '1': 1 }

obj.toString()gives

obj.toString()

"[object Object]"

JSON.stringify(obj)gives

JSON.stringify(obj)

"{"1":1,"a":"a"}"

For .toString(), a default value is returned when the argument type is an object. JSON.stringifyon the other hand returns JSON text, which can be converted back into a JSON object by using JSON.parse

对于.toString(),当参数类型是对象时返回默认值。另一方面,JSON.stringify返回 JSON 文本,可以使用JSON.parse将其转换回 JSON 对象

回答by jAndy

As you might have noticed, while you tried (hopefully), calling .toString()which anyobject inherits (*)from Object.prototype.toString(), returns [object Object].

正如你可能已经注意到,当你尝试(希望),要求.toString()任何对象继承(*)Object.prototype.toString(),退货[object Object]

Thats how its defined internally, returning the internal [Class]name from an object. Of course, other objectscan override this method (remember, its just originally defined on the prototype chain) and return pretty much anything.

这就是它在内部定义的方式,[Class]从对象返回内部名称。当然,其他对象可以覆盖这个方法(记住,它最初只是在原型链上定义的)并返回几乎任何东西。

JSON.stringify()on the other hand, is a method of the JSON object, which kind of serializesan object structure into a string version. Hence, Javascript Object Notation, it will describe an object with all nested structures in pure ascii string.

JSON.stringify()另一方面,是 JSON 对象的一种方法,将对象结构序列化为字符串版本。因此,Javascript Object Notation,它将用纯ascii string描述具有所有嵌套结构的对象。



(*) exception: objects created with Object.create(null);

(*) 异常:创建的对象 Object.create(null);

回答by Nayan Patel

You can use the replacer and space parameter in JSON.stringify, passing the replacer argument as a function you can modify the object and space parameter helps you to give extra space before every key value pair.

您可以在 JSON.stringify 中使用 replacer 和 space 参数,将 replacer 参数作为函数传递,您可以修改 object 和 space 参数帮助您在每个键值对之前留出额外的空间。

const replacer = (key, value) => {
        // Filtering out properties
        if (typeof value === 'number') {
            return 1;
        }
        return value;
    },

    foo = {
        country: 'India',
        state: 'Gujarat',
        district: 45,
        cm: 'car',
        am: 7
    },

    result = JSON.stringify(foo, replacer);

console.log(result) // {"country":"India","state":"Gujarat","district":1,"cm":"car","am":1}

Space argument -

空间论证——

const obj = { a : 1, b:2};

const obj_str = JSON.stringify(obj, null, '     ');// '\t' gives one tab 

console.log(obj_str)

For more details you can visit this link.

有关更多详细信息,您可以访问此链接。