简体   繁体   中英

Prototype.js 1.6.x toJSON misbehaves

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 :(

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM