JSON stringify Array Overriding Issues With Prototype js

Posted By : Himanshu Agarwal | 10-Sep-2017

Ideally below mentioned code gives us output as:

Input:

JSON.stringify({"a":[1,2]})

Output:

"{\"a\":[1,2]}"

 

But if prototype.js is also being used in the project output changes to 

"{\"a\":\"[1, 2]\"}"

The newly formed array has extra quotes "" around it, for removing them we need to use JSON.parse again on the output. Using JSON.parse is not appreciated as it degrades the site performance.

The reason for this conflict is the function JSON.stringify() defined in ECMAScript 5 and above uses the function toJSON() when available on objects. Because Prototype.js defines an Array.prototype.toJSON() function, arrays are first converted to strings using Array.prototype.toJSON() then string quoted by JSON.stringify(), hence the incorrect extra quotes around the arrays.

 

A possible solution without affecting other Prototype dependencies : 

var _json_stringify = JSON.stringify;
JSON.stringify = function(value) {
    var _array_tojson = Array.prototype.toJSON;
    delete Array.prototype.toJSON;
    var r=_json_stringify(value);
    Array.prototype.toJSON = _array_tojson;
    return r;
};

 

Note: There could be other solutions as well to encounter above mentioned problem.

About Author

Author Image
Himanshu Agarwal

He works on Frontend Technologies like Javascript, Angular, HTML, CSS, jQuery.

Request for Proposal

Name is required

Comment is required

Sending message..