我想将 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(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.window
和 document.body.ownerDocument === document
一样。
另外,JSON.stringify
不序列化函数,所以这不是我要找的。p>
`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 不支持,等等。
我不想制作数千个测试用例。我想用通用的方式来测试它们。
我做了一个原型(prototype) 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 重新模板化的项目。
https://stackoverflow.com/questions/2303713/