Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serialize a javascript array

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?.

like image 787
Gandalf Avatar asked Mar 12 '26 13:03

Gandalf


1 Answers

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.

like image 155
Darin Dimitrov Avatar answered Mar 14 '26 02:03

Darin Dimitrov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!