最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - What toString function does JSON stringify use? - Stack Overflow

programmeradmin1浏览0评论

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 badges
Add a ment  | 

1 Answer 1

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.

发布评论

评论列表(0)

  1. 暂无评论