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

我想将DOM节点甚至整个序列化为windowJSON。


例如:


 >> 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.window一如既往document.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不支持localStorageIE 7,等等。


我不想做成千上万的测试用例。我想以通用的方式测试它们。



Smart猫小萌
浏览 699回答 3
3回答

猛跑小猪

您可能会遍历DOM并为其生成纯JS对象表示,然后将其提供给DojoX序列化器。但是,您必须首先决定如何计划将DOM元素,它们的属性和文本节点毫无歧义地映射到JS对象。例如,您将如何表示以下内容?<parent attr1="val1">&nbsp; Some text&nbsp; <child attr2="val2"><grandchild/></child></parent>像这样?{&nbsp; &nbsp; tag: "parent",&nbsp; &nbsp; attributes: [&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; name: "attr1",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; value: "val1"&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; ],&nbsp; &nbsp; children: [&nbsp; &nbsp; &nbsp; &nbsp; "Some text",&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; tag: "child",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; attributes: [&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; name: "attr2",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; value: "val2"&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ],&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; children: [&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; { tag: "grandchild" }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ]&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp;]&nbsp;}我认为DojoX不立即支持DOM序列化的原因可能完全是这样的:需要首先选择一种将DOM映射到JS对象的方案。有没有可以采用的标准方案?您的JS对象会简单地模仿没有任何功能的DOM树吗?我认为您必须首先定义对“将DOM序列化为JSON”的期望。

慕斯王

看来您必须自己编写。JSON序列化数据也可能不是您的任务(DOM兼容性表)的理想选择。您可能必须自己迭代对象,检查属性的类型等等。var functions = [];var strings = [];for( var key in window ) {&nbsp; &nbsp; if( typeof window[key] == 'string' ) {&nbsp; &nbsp; &nbsp; &nbsp; strings[strings.length] = key;&nbsp; &nbsp; } else if( typeof window[key] == 'function' ) {&nbsp; &nbsp; &nbsp; &nbsp; functions[functions.length] = key;&nbsp; &nbsp; } else if( ... ) { ... }}...
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript