What toString function does JSON stringify use?

javascript, json

Solution

   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.

Problem

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?

Original source