即使有循环引用,如何将DOM节点序列化为JSON? [英] How to serialize DOM node to JSON even if there are circular references?
问题描述
我想将DOM节点或甚至整个窗口序列化到JSON。
I want to serialize DOM node or even whole window
to 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()
JSON.stringify(window) // TypeError: Converting circular structure to JSON
问题是JSON默认不支持循环引用。
The problem is JSON does not support circular references by default.
var obj = {}
obj.me = obj
JSON.stringify(obj) // TypeError: Converting circular structure to JSON
窗口
和DOM节点有很多。 window === window.window
as document.body.ownerDocument === document
。
window
and DOM nodes have many of them. window === window.window
as will as document.body.ownerDocument === document
.
另外, JSON.stringify
不会将函数序列化,所以这不是我要找的。 p>
dojox.json .ref
Also, JSON.stringify
does not serialize functions, so this is not what I'm looking for.
`dojox.json.ref.toJson()` can easily serialize object with circular references:
var obj = {}
obj.me = obj
dojox.json.ref.toJson(obj); // {"me":{"$ref":"#"}}
好,不,不能序列化DOM节点
Good, isn't it?
dojox.json.ref.toJson(window) // Error: Can't serialize DOM nodes
对我来说不够好。
我正在为不同的浏览器制作DOM兼容性表。例如,Webkit支持占位符属性,Opera不支持,IE 8支持 localStorage
,IE 7不等等。
I'm trying to make DOM compatibility table for different browsers. For instance, Webkit supports placeholder attribute and Opera doesn't, IE 8 supports localStorage
and IE 7 doesn't, and so on.
我不想做成千上万的测试用例。我想制作通用的方式来测试它们。
I don't want to make thousands of test-cases. I want to make generic way for test them all.
我做了一个原型 NV / dom-dom-dom.com 。
I made a prototype NV/dom-dom-dom.com.
推荐答案
http:// jsonml。 org / 采用语法将XHTML DOM元素转换为JSON。一个例子:
http://jsonml.org/ takes a shot at a grammar for converting XHTML DOM elements into JSON. An an example:
<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重新模板。
Haven't used it yet, but thinking about using it for a project where I want to take any web page and re-template it using mustache.js.
这篇关于即使有循环引用,如何将DOM节点序列化为JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!