English 中文(简体)
JSON. 拼字阵列,造成双重括号
原标题:JSON.stringify array resulting in double brackets
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"}]]

造成双重括号,这给我造成了一些服务器上的问题。

我怎样才能摆脱这双括号?

最佳回答

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

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

<强度> 更新: 如果 val 是一阵列, 您需要适当对待它, 例如 : < a href=" http://jsfiddle. net/ NatJS/1/" rel= "nofollow" > http://jsfidd. 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));​
问题回答

注释区域太小, 不适合此 。

审视一下问题简化的以下内容:

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 应该包含哪些内容,都不是;-)

检查对象上是否定义了 JSON 。 如果定义了, 它可以修改字符串的动作 。





相关问题
ajax login using httpRequest?

I am trying to develop my login script to give feedback to the user if the login is valid or not. Basically if it isn t correct a div box will show saying its wrong, if its correct it will show its ...

Virtual Tour using sketch up, ajax, flash technologies

I want to know if there are existing technology that make your 3d models in sketch into virtual tours, using either Ajax or Flash for web presentation. If there s none, which will be a good approach ...

How can i update div continuously

I have asp.net application where i have a div which showing the value from other site. The value of that site is changing continuously. I want that my div will automatically update in some interval ...

热门标签