1

In Prototype.js 1.6.x try and do

Object.toJSON([{"nodeType":1}])

it should yield

'[{"nodeType":1}]'

as the output string. However it yields '[]'. It appears to skip objects that have nodeType==1. It has something to do with them being DOM elements. Is there a work around to get the correct output?

jsFiddle: http://jsfiddle.net/xPVnr/

EDIT:

Looking at the source it appears toJSON just returns if isElement(obj) is true which is in turn true if obj.nodeType == 1 :(

4
  • Use the newest Prototype.js version instead. It seems to be fixed in 1.7. Dec 12, 2012 at 20:38
  • 1.6.x is creating the problem and it is not under my control to change it.
    – akkishore
    Dec 12, 2012 at 20:42
  • 4
    Well, there are new versions for a reason ;) Maybe you can have a look at the source code of 1.7 and overwrite the function with that code, but that's quite hacky. If you can, request to upgrade to 1.7 (if it does not break anything else). Dec 12, 2012 at 20:48
  • I understand. We actually provide a javascript library to embed into other websites. And hence our library has to work with all possible javascript frameworks out there :)
    – akkishore
    Dec 12, 2012 at 21:03

1 Answer 1

0

Use JSON.stringify but with following tweak to get correct output (in case of Arrays):

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;
};

This takes care of the Array toJSON incompatibility with JSON.stringify and also retains toJSON functionality as other Prototype libraries may depend on it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.