Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What toString function does JSON stringify use?

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?

like image 231
Ionică Bizău Avatar asked Jan 04 '14 19:01

Ionică Bizău


People also ask

Does JSON Stringify use toString?

JSON. stringify() is a function of the JSON object that will create a string of the object within the pattern adopted by JSON. By a near coincidence (not 100% because JSON is based on JS notation) the toString() method gives the same result at first.

How do I use JSON toString?

Use the JavaScript function JSON. stringify() to convert it into a string. const myJSON = JSON. stringify(obj);

What is the function toString () method?

For user-defined Function objects, the toString method returns a string containing the source text segment which was used to define the function. JavaScript calls the toString method automatically when a Function is to be represented as a text value, e.g. when a function is concatenated with a string.

What is difference between toJSONString and toString?

valueToString(Object) method, line 1460). Then in toString() the exception is caught an toString() returns null. JSONString toJSONString() throws exception or return non String object, the exception is ignored (see JSONObject. valueToString(Object, int, int) method, line 1511).


1 Answers

   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.

like image 64
kybernetikos Avatar answered Sep 22 '22 00:09

kybernetikos