相关疑难解决方法(0)

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

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

例如:

 >> serialize(document)
    -> {
      "URL": "http://stackoverflow.com/posts/2303713",
      "body": {
        "aLink": "",
        "attributes": [
          "getNamedItem": "function getNamedItem() { [native code] }",
          ...
        ],
        ...
        "ownerDocument": "#" // recursive link here
      },
      ...
    }
Run Code Online (Sandbox Code Playgroud)

JSON.stringify()

JSON.stringify(window) // TypeError: Converting circular structure to JSON
Run Code Online (Sandbox Code Playgroud)

问题是JSON默认不支持循环引用.

var obj = {}
obj.me = obj
JSON.stringify(obj) // TypeError: Converting circular structure to JSON
Run Code Online (Sandbox Code Playgroud)

window和DOM节点有很多.window === window.window将如此document.body.ownerDocument === document.

此外,JSON.stringify不序列化函数,所以这不是我想要的.

dojox.json.ref

 `dojox.json.ref.toJson()` can easily serialize object with …
Run Code Online (Sandbox Code Playgroud)

javascript serialization json dom circular-reference

48
推荐指数
3
解决办法
6万
查看次数