javascript - 即使有循环引用,如何将 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 不序列化函数,所以这不是我要找的。​​p>

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 重新模板化的项目。

https://stackoverflow.com/questions/2303713/

相关文章:

json - bash 中的转义字符(对于 JSON)

c# - EF 4.1 - 代码优先 - JSON 循环引用序列化错误

android - 如何在Android中解析json字符串?

json - 使用逗号拆分 NSString

java - 更新 JSONObject 中的元素

c# - 使用 Nancy 返回包含有效 Json 的字符串

javascript - 如何使用 Typeahead.js 0.10 一步一步/远程/预取/本地

php - 从 PHP 中的 JSON POST 读取 HTTP 请求正文的问题

javascript - 如何从 AJAX 调用中返回一个数组?

json - JSON 表示中的链接关系