对象字符串转换为JSON(抛出错误)

Object stringify to JSON(throws error)

本文关键字:出错 错误 JSON 字符串 转换 对象      更新时间:2024-02-17

在尝试将对象转换为JSON时遇到问题。我正在创建一个棱角分明的网络应用程序。

下面是我转换为对象的json:

var array = {
    "game": [{
        "Time (magazine)": [{
            "AARP Bulletin": []
        }, {
            "AARP The Magazine": []
        }]
    }, {
        "Ludwig Wittgenstein": [{
            "Wittgenstein": []
        }, {
            "20th century philosophy": [{
                "16th-century philosophy": [{
                    "19th-century philosophy": []
                }]
            }, {
                "17th-century philosophy": []
            }]
        }]
    }]
};

并使用此方法转换为首选json结构:

function restyle(obj) {
  Object.keys(obj).forEach(function (k) {
    obj.name = k;
    obj.child = obj[k];
    delete obj[k];
    obj.child.forEach(restyle);
  });
};

然而,当我在通过restyle方法后尝试控制台记录数组变量时。我得到错误

TypeError:将循环结构转换为JSON

我尝试使用JSON.stringfy(数组)。同样的错误出现了。

我试着在Firebug的控制台中以如下方式运行您的代码,它对我有效:

function restyle(obj) {
  Object.keys(obj).forEach(function (k) {
    obj.name = k;
    obj.child = obj[k];
    delete obj[k];
    obj.child.forEach(restyle);
  });
};
var array = {
    "game": [{
        "Time (magazine)": [{
            "AARP Bulletin": []
        }, {
            "AARP The Magazine": []
        }]
    }, {
        "Ludwig Wittgenstein": [{
            "Wittgenstein": []
        }, {
            "20th century philosophy": [{
                "16th-century philosophy": [{
                    "19th-century philosophy": []
                }]
            }, {
                "17th-century philosophy": []
            }]
        }]
    }]
};
restyle(array);
console.log(JSON.stringify(array));

我得到以下作为控制台输出:

{"name":"game","child":[{"name":"Time (magazine)","child":[{"name":"AARP Bulletin","child":[]},{"name":"AARP The Magazine","child":[]}]},{"name":"Ludwig Wittgenstein","child":[{"name":"Wittgenstein","child":[]},{"name":"20th century philosophy","child":[{"name":"16th-century philosophy","child":[{"name":"19th-century philosophy","child":[]}]},{"name":"17th-century philosophy","child":[]}]}]}]}

这就是你想要做的吗?

相关文章: