JSON Basics - Array
(Page 3 of 5 )
Unlike JSON objects, JSON arrays are enclosed between square braces [ ]. The JSON array is an ordered sequence of values separated by a comma (,). The values can be any of the primitive types as well as the two structures, JSON objects and JSON arrays. Here is a JSON array variable with four string values.
var myJsonArray=["Red", "Blue", "Yellow", "Magenta"];
You will be able to access an array item from its position (0 based) as shown in the following listing.
<SCRIPT LANGUAGE="JavaScript">
var myJsonArray=["Red", "Blue", "Yellow", "Magenta"];
for (i=0; i<4; i++){
document.write("<b>myJsonArray["+i+"]</b>="+ myJsonArray[i]+"<br>");
}
</SCRIPT>
The displayed output when this script is executed is as shown in the next picture.

It is possible to have an array whose elements are of different types. Array items can be objects and arrays as well, as shown in the next listing.
<SCRIPT LANGUAGE="JavaScript">
//Array with different types
myJA2=["red", 1, null, true];
document.write("<b>myJA2:</b> " + myJA2[2]);
document.write("<p></p>");
//Nested array
myJA3=["red",1,["a", "b", "c"], false];
document.write("<b>myJA3[2][1]:</b> " + myJA3[2][1]);
document.write("<p></p>");
//Object in an array
myJA4=["red", {"Yes":"Yes, you do", "No":"No, you do not"}, 2];
document.write("<b>myJA4[1].Yes: </b>"+ myJA4[1].Yes);
</SCRIPT>
The displayed output when this script is executed is as shown in the next picture. Notice how the inner array and the object inside the array are accessed.

Next: JSON and XML >>
More JavaScript Articles
More By Jayaram Krishnaswamy