JSON.stringify数组导致双括号

时间:2012-05-22 11:56:20

标签: jquery ajax json

var DTO = [];

$.each(data.Foobars, function(i, val){
    DTO.push(val);
});

//example of a stringified object in the array:
// var val = {"a":"1","b":"2","c":"3"};

var jsonString = JSON.stringify(DTO); 

在数组中有一个对象,'jsonString'看起来像:

[{"a":"1","b":"2","c":"3"}]

有多个:

[[{"a":"1","b":"2","c":"3"}, {"a":"1","b":"2","c":"3"}]]

导致双括号,这导致我在服务器端出现一些问题。

我怎样才能摆脱双括号?感谢

3 个答案:

答案 0 :(得分:4)

您确定val对象本身不是数组吗?

在我的小测试中:http://jsfiddle.net/NatJS/,JSON.stringify工作正常。

更新:如果val是一个数组,则需要对其进行适当处理,例如:http://jsfiddle.net/NatJS/1/

var a = [{ a: 1, b: 2, c: 3},{ d: 10, e: 11, f: 12}];
//var a = { a: 1, b: 2, c: 3}
var j = [];


if (a.length) { // cheap way to check if a an an array; implement something like mooTools.typeOf if you want something more robust
    while (a.length > 0) {
        j.push(a.pop());               
    }
}
else {
    j.push(a);
}

console.log(JSON.stringify(j));​

答案 1 :(得分:1)

评论区域太小了。

看看以下问题的简化:

var DTO = [];

DTO.push({"a":"1","b":"2","c":"3"});
DTO.push({"a":"1","b":"2","c":"3"});

console.log(JSON.stringify(DTO));

它会显示:

[{"a":"1","b":"2","c":"3"},{"a":"1","b":"2","c":"3"}]

结论:无论你认为val应该包含它,都不是; - )

答案 2 :(得分:0)

检查对象上是否定义了toJSON。如果已定义,则可以修改stringify的行为。