Johan
Johan

Reputation: 35194

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); 

With one object in the array the ´jsonString´ would look like:

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

With more than one:

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

Resulting in double brackets, which is causing me some problems serverside.

How can i get rid of the double brackets? Thanks

Upvotes: 1

Views: 18164

Answers (3)

Jyaif
Jyaif

Reputation: 1095

Check if toJSON is defined on your object. If it is defined, it can modify the behavior of stringify.

Upvotes: 0

Thach Mai
Thach Mai

Reputation: 945

Are you sure the val object is not an array itself?

In my little test: http://jsfiddle.net/NatJS/, JSON.stringify works just fine.

Update: if val is an array, you need to treat it appropriately, such as: 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));​

Upvotes: 4

Ja͢ck
Ja͢ck

Reputation: 173562

The comment area is too small for this.

Take a look at the following simplification of your problem:

var DTO = [];

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

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

It will show:

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

Conclusion: whatever you think val should contain it's not ;-)

Upvotes: 1

Related Questions