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

时间:2016-04-07 15:50:53

标签: javascript angularjs json

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

下面是我转换为object的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(数组)。出现相同的错误。

1 个答案:

答案 0 :(得分:0)

我尝试在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":[]}]}]}]}

这是你想要做的吗?