gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 12:45:48 25 4
gpt4 key购买 nike

我想将 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 不支持,等等。

我不想制作数千个测试用例。我想用通用的方式来测试它们。

2013 年 6 月更新

我做了一个原型(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 重新模板化的项目。

关于javascript - 即使有循环引用,如何将 DOM 节点序列化为 JSON?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2303713/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com