Uncaught TypeError: Converting circular structure to JSON

僤鯓⒐⒋嵵緔 提交于 2019-11-30 06:02:21

You should not convert a DOM element to JSON directly.

While - like you already experienced - it fails e.g. in Chrome, the results may also be unexpected.

The reason for this is because the data is circular:

A Node has the property childNode containing all its children and the property parentNode pointing to the parent.

The JSON format does not support references, so it will need to follow the properties until an end is reached, but because a child points to its parent which has a list of its children, this is an endless loop, that’s the reason why you get the error:

Uncaught TypeError: Converting circular structure to JSON

Even if this is resolved by the browser you may have other problems. Because not only childNodes exist but also childElements. The same is for parentNode/parentElement, then you also have nextSibling, prevSibling, firstChild, lastChild, ... that would probably also be followed, so you would end up in the terrifying large JSON file containing a butch of duplicate data.

You need to use the .innerHtml property of the DOM element instead of converting the entire DOM element. So you should be looking to have something like:

JSON.stringify(table.tBodies[0].innerHTML)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!