admin管理员组文章数量:1303411
I want to create my own toString
function for a data type.
Let's take an example:
JSON.stringify({}) // "{}"
I want "test"
to be returned. So, I tried to modify the object prototype:
Object.prototype.toString = function () { return "test"; }
Then: JSON.stringify({})
returns "{}"
, too.
I am sure that there is a function that can be rewritten to return custom values.
What's that function?
I want to create my own toString
function for a data type.
Let's take an example:
JSON.stringify({}) // "{}"
I want "test"
to be returned. So, I tried to modify the object prototype:
Object.prototype.toString = function () { return "test"; }
Then: JSON.stringify({})
returns "{}"
, too.
I am sure that there is a function that can be rewritten to return custom values.
What's that function?
Share Improve this question asked Jan 4, 2014 at 19:55 Ionică BizăuIonică Bizău 113k93 gold badges307 silver badges487 bronze badges1 Answer
Reset to default 13 function MyObj() {};
MyObj.prototype.toJSON = function(){return "test";}
JSON.stringify(new MyObj())
""test""
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.
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""
For more information on the translation function see Using native JSON.
本文标签: javascriptWhat toString function does JSON stringify useStack Overflow
版权声明:本文标题:javascript - What toString function does JSON stringify use? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741740208a2395248.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论