Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript JSON.stringify function is not working

I have tried to convert a JS object into JSON.

JSON.stringify({a:1, toJSON: function(){}})

Native JSON stringify is not working as expected. JSON stringify executes toJSON function in JS object internally. I have overwritten native code as follows,

// Adding try catch for non JSON support browsers.
try{
 _jsonStringify = JSON.stringify;
 JSON.stringify = function(object){
    var fnCopy = object.toJSON; 
    object.toJSON = undefined;
    var result =  _jsonStringify(object);
    object.toJSON = fnCopy;
    return result;      
 };
}catch(e){}

It is working fine. is there any other better way to do this?. is there any specific reason in native code execute toJSON function in input object?

like image 548
HILARUDEEN S ALLAUDEEN Avatar asked May 27 '14 18:05

HILARUDEEN S ALLAUDEEN


People also ask

How do I Stringify a function in JSON?

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

Why JSON Stringify does not work on array?

The JSON array data type cannot have named keys on an array. When you pass a JavaScript array to JSON. stringify the named properties will be ignored. If you want named properties, use an Object, not an Array.

Does JSON Stringify return string?

Return Value: It returns a string for a given value. Example: The below is the example of the JSON stringify() Method.

What can I use instead of Stringify?

You should use the library json2. js .


1 Answers

This is because JSON.stringify will return the return value of the toJSON function if it exists (Source).

For example:

JSON.stringify({a:1, toJSON: function(){ return "a"; }});

Will return:

"a"

This behaviour is described on MDN. The reason for this is so that you can customize the behaviour of the serialization. For example, say I only want to serialize the IDs of the Animal class in this example. I could do the following:

var Animal = function(id, name) {
    this.AnimalID = id;
    this.Name     = name;
};

Animal.prototype.toJSON = function() {
    return this.AnimalID;
};

var animals = [];

animals.push(new Animal(1, "Giraffe"));
animals.push(new Animal(2, "Kangaroo"));

JSON.stringify(animals); // Outputs [1,2]

If you do not want this behaviour then your current method works well; however, I would recommend not overwriting the behaviour of JSON.stringify, but rather name your method something else. An external library might be using the toJSON function in an object and it could lead to unexpected results.

like image 114
David Sherret Avatar answered Sep 20 '22 12:09

David Sherret