JSON Arrays
Arrays as JSON Objects
Example
[ "Google", "tutorialpro", "Taobao" ]
JSON arrays are written inside square brackets.
Square brackets []
hold arrays which are ordered collections of values. An array begins with a left square bracket [
and ends with a right square bracket ]
, with values separated by commas ,
.
In JSON, array values must be of valid JSON data types (string, number, object, array, boolean, or null).
In JavaScript, array values can be the above JSON data types, or JavaScript expressions, including functions, dates, and undefined.
Arrays in JSON Objects
The value of an object property can be an array:
Example
{
"name":"网站",
"num":3,
"sites":[ "Google", "tutorialpro", "Taobao" ]
}
We can access array elements using their index values:
Example
x = myObj.sites[0];
Looping Through Arrays
You can use a for-in loop to access array elements:
Example
for (i in myObj.sites) {
x += myObj.sites[i] + "<br>";
}
You can also use a for loop:
Example
for (i = 0; i < myObj.sites.length; i++) {
x += myObj.sites[i] + "<br>";
}
Arrays in Nested JSON Objects
Arrays in JSON objects can contain another array or another JSON object:
Example
myObj = {
"name":"网站",
"num":3,
"sites": [
{ "name":"Google", "info":[ "Android", "Google 搜索", "Google 翻译" ] },
{ "name":"tutorialpro", "info":[ "tutorialpro.org", "tutorialpro", "geek" ] },
{ "name":"ebay", "info":[ "good", "network" ] }
]
}
We can use a for-in loop to iterate through each array:
Example
for (i in myObj.sites) {
x += "<h1>" + myObj.sites[i].name + "</h1>";
for (j in myObj.sites[i].info) {
x += myObj.sites[i].info[j] + "<br>";
}
}
Modifying Array Values
You can modify array values using their index values:
Example
myObj.sites[1] = "Github";
Deleting Array Elements
We can use the delete keyword to remove array elements:
Example
delete myObj.sites[1];