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.

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

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

Example
{
"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.

Example
x = jsonObj.cars[0];

Sample JSON array objects.
snippet
//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
{"employees":[
{"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.

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

Using for loop
Example
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.

snippet
jsonObj = {
"name":"John",
"age":30,
"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.

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

Example
delete jsonObj.cars[1];
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents +