如何调试JSON.stringify正在报告的循环引用

时间:2019-05-03 20:13:29

标签: jquery arrays json ecmascript-5

调用JSON stringify时出现循环引用异常,但找不到循环引用。看来jQuery是罪魁祸首,但我看不到这个问题,无法进入JSON字符串化。

const list = $('.use-in-reporting-checkbox:checkbox:checked').map(function() 
{
    return this.value;
});

const dataPacket = {
    datasetIDs: list
};

try {
    const real = JSON.stringify(dataPacket);

} catch (error) {
    processError(error);
}

"Error reports: Converting circular structure to JSON
    --> starting at object with constructor 'Object'
    property 'selectorData' -> object with constructor 'Object'
    |     property 'elements' -> object with constructor 'Array'
    --- index 0 closes the circle"

But, inspection of dataPacket just shows: "datasetIDs init (37)" with the 
list of checkbox values. Not sure how to debug this.

1 个答案:

答案 0 :(得分:1)

发生此错误是因为您获取了jQuery对象而不是所需的值。

.map方法返回jQuery对象,应通过 get -call解析:

const ids = $('.use-in-reporting-checkbox:checkbox:checked').map(function() 
{
    return this.id;
}).get();

替代方式:

const ids = jQuery.map($('.use-in-reporting-checkbox:checkbox:checked'), function(v) 
{
    return v.id;
});