检测JavaScript对象是否具有引用DOM元素的某些属性
我想将JavaScript对象序列化为JSON格式,然后反序列化它们 显而易见的解决方案是使用JSON.stringify。关键是关于JSON.stringify的主要问题是,它在尝试序列化循环对象时返回错误。返回的错误如下所示检测JavaScript对象是否具有引用DOM元素的某些属性,javascript,json,dom,serialization,Javascript,Json,Dom,Serialization,我想将JavaScript对象序列化为JSON格式,然后反序列化它们 显而易见的解决方案是使用JSON.stringify。关键是关于JSON.stringify的主要问题是,它在尝试序列化循环对象时返回错误。返回的错误如下所示 TypeError: Converting circular structure to JSON 一些建议的解决方案,如and,可以作为一种变通方法,以便能够序列化和反序列化循环对象 这些解决方案的一个问题是,它们不允许序列化引用DOM元素的循环对象或包含指向DOM元
TypeError: Converting circular structure to JSON
一些建议的解决方案,如and,可以作为一种变通方法,以便能够序列化和反序列化循环对象
这些解决方案的一个问题是,它们不允许序列化引用DOM元素的循环对象或包含指向DOM元素的属性的最差循环对象。例如,使用cycle.js返回
Failed to read the 'selectionDirection' property from 'HTMLInputElement': The input element's type ('image') does not support selection.
我考虑过使用document.containsobjName检测对DOM元素的引用,当objName对象引用DOM树中的现有元素时,document.containsobjName返回true。如果我能够检测到这些元素,我将标记这些引用并删除它们,以便能够使用cycle.js序列化一个新对象,并在反序列化后将它们重新指向DOM元素
我的问题是,我事先不知道对象是否有指向DOM元素的属性,当我想重新解析所有属性和属性的属性时,我将无法停止解析,因为对象可能是循环原始问题,我将得到以下错误
Maximum call stack size exceeded
有什么线索吗?我找到了上述问题的解决方案: 我所做的是,我添加了两行来标记指向DOM元素的对象,并打断它们,以便不在其属性内搜索。我突出显示了cycle.js中添加的行:
/*
cycle.js
2013-02-19
Public Domain.
NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
This code should be minified before deployment.
See http://javascript.crockford.com/jsmin.html
USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
NOT CONTROL.
*/
/*jslint evil: true, regexp: true */
/*members $ref, apply, call, decycle, hasOwnProperty, length, prototype, push,
retrocycle, stringify, test, toString
*/
if (typeof JSON.decycle !== 'function') {
JSON.decycle = function decycle(object) {
'use strict';
// Make a deep copy of an object or array, assuring that there is at most
// one instance of each object or array in the resulting structure. The
// duplicate references (which might be forming cycles) are replaced with
// an object of the form
// {$ref: PATH}
// where the PATH is a JSONPath string that locates the first occurance.
// So,
// var a = [];
// a[0] = a;
// return JSON.stringify(JSON.decycle(a));
// produces the string '[{"$ref":"$"}]'.
// JSONPath is used to locate the unique object. $ indicates the top level of
// the object or array. [NUMBER] or [STRING] indicates a child member or
// property.
var objects = [], // Keep a reference to each unique object or array
paths = []; // Keep the path to each unique object or array
return (function derez(value, path) {
// The derez recurses through the object, producing the deep copy.
var i, // The loop counter
name, // Property name
nu; // The new object or array
// typeof null === 'object', so go on if this value is really an object but not
// one of the weird builtin objects.
if (typeof value === 'object' && value !== null &&
!(value instanceof Boolean) &&
!(value instanceof Date) &&
!(value instanceof Number) &&
!(value instanceof RegExp) &&
!(value instanceof String)) {
// If the value is an object or array, look to see if we have already
// encountered it. If so, return a $ref/path object. This is a hard way,
// linear search that will get slower as the number of unique objects grows.
/* ************************************************************* */
/* ******************** START OF ADDED CODE ******************** */
/* ************************************************************* */
if (document.contains(value))
return {$ref: "TODO mark the position of elements in DOM tree"};
/* ************************************************************* */
/* ********************* END OF ADDED CODE ********************* */
/* ************************************************************* */
for (i = 0; i < objects.length; i += 1) {
if (objects[i] === value) {
return {$ref: paths[i]};
}
}
// Otherwise, accumulate the unique value and its path.
objects.push(value);
paths.push(path);
// If it is an array, replicate the array.
if (Object.prototype.toString.apply(value) === '[object Array]') {
nu = [];
for (i = 0; i < value.length; i += 1) {
nu[i] = derez(value[i], path + '[' + i + ']');
}
} else {
// If it is an object, replicate the object.
nu = {};
for (name in value) {
if (Object.prototype.hasOwnProperty.call(value, name)) {
nu[name] = derez(value[name],
path + '[' + JSON.stringify(name) + ']');
}
}
}
return nu;
}
return value;
}(object, '$'));
};
}
if (typeof JSON.retrocycle !== 'function') {
JSON.retrocycle = function retrocycle($) {
'use strict';
// Restore an object that was reduced by decycle. Members whose values are
// objects of the form
// {$ref: PATH}
// are replaced with references to the value found by the PATH. This will
// restore cycles. The object will be mutated.
// The eval function is used to locate the values described by a PATH. The
// root object is kept in a $ variable. A regular expression is used to
// assure that the PATH is extremely well formed. The regexp contains nested
// * quantifiers. That has been known to have extremely bad performance
// problems on some browsers for very long strings. A PATH is expected to be
// reasonably short. A PATH is allowed to belong to a very restricted subset of
// Goessner's JSONPath.
// So,
// var s = '[{"$ref":"$"}]';
// return JSON.retrocycle(JSON.parse(s));
// produces an array containing a single element which is the array itself.
var px =
/^\$(?:\[(?:\d+|\"(?:[^\\\"\u0000-\u001f]|\\([\\\"\/bfnrt]|u[0-9a-zA-Z]{4}))*\")\])*$/;
(function rez(value) {
// The rez function walks recursively through the object looking for $ref
// properties. When it finds one that has a value that is a path, then it
// replaces the $ref object with a reference to the value that is found by
// the path.
var i, item, name, path;
if (value && typeof value === 'object') {
if (Object.prototype.toString.apply(value) === '[object Array]') {
for (i = 0; i < value.length; i += 1) {
item = value[i];
if (item && typeof item === 'object') {
path = item.$ref;
if (typeof path === 'string' && px.test(path)) {
value[i] = eval(path);
} else {
rez(item);
}
}
}
} else {
for (name in value) {
if (typeof value[name] === 'object') {
item = value[name];
if (item) {
path = item.$ref;
if (typeof path === 'string' && px.test(path)) {
value[name] = eval(path);
} else {
rez(item);
}
}
}
}
}
}
}($));
return $;
};
}
我在jsfiddle.net中添加了一个脚本,在jsfiddle上的chrome浏览器上或本地尝试,firefox 32.0.3无法正常工作。下一步是找到一种方法来检测DOM元素的位置,以便在序列化对象后重新建立引用,并在没有ID的情况下对其进行反序列化。您能提供您试图在json中记住的对象吗?netI在jsfiddle.net上尝试了我的整个脚本,它在firefox和chrome之间以及在jsfiddle上使用它和在我的本地主机上作为文件使用它之间的行为有所不同。下面是我在jsfiddle.net中的示例。我请求您在本地主机上试用。确切地说,我的目标是:var obj=新目标;obj.x=1;对象y=2;obj.z=obj;obj.div=document.getElementById'div';div可以是任何DOM元素,我更新了中的警报以使其更具表达性我认为使用HtmleElement的值instanceof而不是document.containsvalue更为实用。至于保存html元素,您可以保存它的id,或者如果它没有id供将来引用,则为其分配一个新id。是的,使用HtmleElement的值instanceof更实用。我将至少暂时使用id: