PrototypeJS version 1.6.0.2 Overrides JSON.parse and JSON.stringify and breaks socket.io functionality

PrototypeJS version 1.6.0.2 Overrides JSON.parse and JSON.stringify and breaks socket.io functionality

Problem

Basically, socket.io uses nativeJSON to enconde and decode packets, and my problem is that I am obliged to use this version of prototype which changes JSON behaviour. When I should get in the server something like:

socket.on('event', function (a, b, c), I get socket.on('event', function ([a, b, c], undefined, undefined).

One solution is to comment this lines on json.js:

/* socket.io-client/lib/json.js
if (nativeJSON && nativeJSON.parse){
    return exports.JSON = {
      parse: nativeJSON.parse
    , stringify: nativeJSON.stringify
    };
  }
*/

but this change affects performance seriously.

Is there a way to recover native JSON functionality? Would it be possible to create a hidden iframe just to clone the JSON object to restore the old functionality?

Problem courtesy of: Leo

Solution

One solution is to kill Prototype’s toJSON() extension methods:

if(window.Prototype) {
    delete Object.prototype.toJSON;
    delete Array.prototype.toJSON;
    delete Hash.prototype.toJSON;
    delete String.prototype.toJSON;
}

Then you should be able to use the browser’s native JSON.parse/stringify methods without issue.

Solution courtesy of: PP_vinnieg

Discussion

Leave a Reply

Your email address will not be published. Required fields are marked *