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?
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.
Use the JavaScript function JSON. stringify() to convert it into a string. const myJSON = JSON. stringify(obj);
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.
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With