问题描述
我想将 DOM 节点甚至整个 window
序列化为 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(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
window
和 DOM 节点有很多.window === window.window
和 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":"#"}}
很好,不是吗?
dojox.json.ref.toJson(window) // Error: Can't serialize DOM nodes
对我来说还不够好.
我正在尝试为不同的浏览器制作 DOM 兼容性表.例如,Webkit 支持 placeholder 属性而 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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!