Reputation: 13693
I have observed that in php you can encode an array and the resulting json does not carry the square brackets.However,in my javascript array,
var arrCars = new Array("Toyota", "Mercedes", "BMW");
var jsonStr = JSON.stringify(arrCars);
alert(jsonStr);
i keep getting the square brackets.I have also noticed that if i use json stringfy,
var foo = {};
foo.bar = "new property";
foo.baz = 3;
var JSONfoo = JSON.stringify(foo);
i get the json without the square just like i wanted.What must i do to my array to do away with the brackets?.
Upvotes: 3
Views: 5651
Reputation: 10117
Not sure why you don't want brackets, since brackets are the normal way to make an array literal (as opposed to using the Array() function, as you do, which is way old-school)
If you want the JSON without the brackets, such as if you are building a bigger JSON string or something, you can use something like this:
function jsonifyArrayWithoutBrackets(a) {
var output = [];
for (var i=0; i<a.length; i++)
output.push(JSON.stringify(a[i]));
return output.join(',');
}
Or, obviously, just trim the brackets off after using a single call to JSON.stringify().
Upvotes: 1
Reputation: 700840
The correct JSON for the array in your first example is ["Toyota","Mercedes","BMW"]
, and the correct JSON for the object in your second example is either {"bar":"new property","baz":3}
or {"baz":3,"bar":"new property"}
.
A JSON string contains either an object or an array, so it always has either curly brackets {}
or square brackets []
.
If you get anything else, the result is not correct. If you expect anything else, your expectation is wrong.
If you want the curly brackets instead of the square brackets, you have to serialise an object, not an array.
Upvotes: 1
Reputation: 1039498
There's a difference between an array ([]
) and an object ({}
) in javascript. Your first example uses an array. Your second example uses an object. The main difference is that when you have an array ([]
) the index can only be a zero based integer. Whereas an object can have property names that are strings.
Upvotes: 2