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.
More From Oodles
Ready to innovate? Let's get in touch
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Himanshu Agarwal
He works on Frontend Technologies like Javascript, Angular, HTML, CSS, jQuery.