JSON Arrays

Arrays in JSON are almost the same as arrays in JavaScript. In JSON, array values must be of type string, number, object, array, boolean or null.

["Audi", "BMW", "Ferrari"]

Arrays in JSON Objects
Arrays can be values of an object property.

"name": "John",
"age": 32,
"cars": ["Audi", "BMW", "Ferrari"]

Accessing Array Values
You access the array values by using the index number just like javascript arrays.

x = jsonObj.cars[0];

Sample JSON array objects.
//JSON Array of Strings
["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]

//JSON Array of Numbers
[12, 34, 56, 43, 95]

//JSON Array of Booleans
[true, true, false, false, true]

//JSON Array of Objects
{"name":"Ram", "age":23},
{"name":"Shyam", "age":28},
{"name":"John", "age":33},
{"name":"Bob", "age":41}

//JSON Multidimensional Array
[ "a", "b", "c" ],
[ "m", "n", "o" ],
[ "x", "y", "z" ]

Looping Through an Array
You can access array values by using a for-in loop or for loop.

for (i in jsonObj.cars) {
x += jsonObj.cars[i];

Using for loop
for (i = 0; i < jsonObj.cars.length; i++) {
x += jsonObj.cars[i];

Nested Arrays in JSON Objects
Values in an array can also be another array, or even another JSON object.

jsonObj = {
"cars": [
{ "name":"Audi", "models":[ "A3 Sportback", "A4", "Q4" ] },
{ "name":"BMW", "models":[ "X5", "320", "X3" ] },
{ "name":"Ferrari", "models":[ "512 TR", "488 GTB", "360 Modena" ] }

To access arrays inside arrays, use a for-in loop for each array.

for (i in jsonObj.cars) {
x += "<h2>" + jsonObj.cars[i].name + "</h2>";
for (j in jsonObj.cars[i].models) {
x += jsonObj.cars[i].models[j];

Modify Array Values
Use the index number to modify an array.

jsonObj.cars[1] = "Mercedes";

Delete Array Items
Use the delete keyword to delete items from an array.

delete jsonObj.cars[1];
Related Tutorial