JSON stringify使用什么toString函数? [英] What toString function does JSON stringify use?
问题描述
我想为数据类型创建自己的 toString
函数。
I want to create my own toString
function for a data type.
让我们举一个例子:
JSON.stringify({}) // "{}"
我希望test
返回。所以,我试图修改对象原型:
I want "test"
to be returned. So, I tried to modify the object prototype:
Object.prototype.toString = function () { return "test"; }
然后: JSON.stringify({})
也返回{}
。
我确信有一个可以重写的函数返回自定义值。
I am sure that there is a function that can be rewritten to return custom values.
这是什么功能?
推荐答案
function MyObj() {};
MyObj.prototype.toJSON = function(){return "test";}
JSON.stringify(new MyObj())
""test""
JSON在其字符串化的对象上查找 toJSON
函数。但是请注意,您没有从返回一个字符串到JSON
,而是返回一个字符串化的对象来代替您传入的对象。在这种情况下,我返回了一个字符串,这就是为什么返回值在它周围有额外的引号。
JSON looks for toJSON
functions on the objects it stringifies. Notice however that you don't return a string from toJSON
, you return an object that gets stringified in place of the object you passed in. In this case I returned a string, so that's why the return value has extra quotes around it.
你也可以用传递给stringify的翻译函数做同样的事情。
You can also do the same thing with a translation function passed to stringify.
var x = {};
JSON.stringify(x, function(key, value){
if (value===x) {return "test";} else {return value;}
});
""test""
有关翻译功能的更多信息,请参阅使用原生JSON 。
For more information on the translation function see Using native JSON.
这篇关于JSON stringify使用什么toString函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!