即使有循环引用,如何将DOM节点序列化为JSON?

我想序列化DOM节点,甚至整个window到JSON。

例如:

  >> serialize(document) -> { "URL": "http://stackoverflow.com/posts/2303713", "body": { "aLink": "", "attributes": [ "getNamedItem": "function getNamedItem() { [native code] }", ... ], ... "ownerDocument": "#" // recursive link here }, ... } 

JSON.stringify()

 JSON.stringify(window) // TypeError: Converting circular structure to JSON 

问题是JSON默认不支持循环引用。

 var obj = {} obj.me = obj JSON.stringify(obj) // TypeError: Converting circular structure to JSON 

window和DOM节点有很多。 window === window.windowdocument.body.ownerDocument === document

另外, JSON.stringify不会序列化函数,所以这不是我正在寻找的。

dojox.json.ref

  `dojox.json.ref.toJson()` can easily serialize object with circular references: var obj = {} obj.me = obj dojox.json.ref.toJson(obj); // {"me":{"$ref":"#"}} 

好,不是吗?

  dojox.json.ref.toJson(window) // Error: Can't serialize DOM nodes 

对我来说还不够好。

为什么?

我试图让不同的浏览器的DOM兼容性表。 例如,Webkit支持占位符属性和Opera不支持,IE 8支持localStorage和IE 7不支持,等等。

我不想做成千上万的testing用例。 我想要通用的方式来testing它们。

更新,2013年6月

我做了一个原型NV / dom-dom-dom.com

http://jsonml.org/将XHTML DOM元素转换为JSON的语法。 举个例子:

 <ul> <li style="color:red">First Item</li> <li title="Some hover text." style="color:green">Second Item</li> <li><span class="code-example-third">Third</span> Item</li> </ul> 

 ["ul", ["li", {"style": "color:red"}, "First Item"], ["li", {"title": "Some hover text.", "style": "color:green"}, "Second Item"], ["li", ["span", {"class": "code-example-third"}, "Third"], " Item" ] ] 

还没有使用它,但考虑将其用于我想要使用任何网页并使用mustache.js重新模板的项目。

您可能会遍历DOM并生成纯JS对象表示,然后将其馈送到DojoX序列化程序。 但是,您必须首先决定如何计划将DOM元素,它们的属性和文本节点映射到JS对象,而没有歧义。 例如,您将如何表示以下内容?

 <parent attr1="val1"> Some text <child attr2="val2"><grandchild/></child> </parent> 

喜欢这个?

 { tag: "parent", attributes: [ { name: "attr1", value: "val1" } ], children: [ "Some text", { tag: "child", attributes: [ { name: "attr2", value: "val2" } ], children: [ { tag: "grandchild" } ] } ] } 

我认为DojoX不会立即支持DOM序列化的一个原因可能就是:首先需要select一个将DOM映射到JS对象的scheme。 有没有可以采用的标准scheme? 你的JS对象是否会简单地模仿一个没有任何函数的DOM树? 我认为你必须首先定义你的期望是从“序列化DOM到JSON”。

我发现这一点 ,当我试图将XMLstring转换为JSON时,它非常适合我。

 XMLObjectifier.xmlToJSON(XMLObjectifier.textToXML(xmlString)); 

也许这会有所帮助。

看起来你必须自己写。 JSON序列化的数据可能也不是您的任务(DOM兼容性表)的完美select。 你可能不得不迭代你自己的对象,检查属性的types等等。

 var functions = []; var strings = []; for( var key in window ) { if( typeof window[key] == 'string' ) { strings[strings.length] = key; } else if( typeof window[key] == 'function' ) { functions[functions.length] = key; } else if( ... ) { ... } } ...