JSON Arrays


Arrays as JSON Objects

Example

[ "Google", "Example", "Taobao" ]

JSON arrays are written inside square brackets.

Square brackets[]The stored array is an ordered collection of values. An array begins with a left square bracket[starts, a right square bracket]ends, values are separated by commas,separated.

Array values in JSON must be 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, andundefined。


Arrays in JSON Objects

The value of an object property can be an array:

Example

{ "name":"Websites", "num":3, "sites":[ "Google", "Example", "Taobao" ] }

We can access arrays using index values:

Example

x = myObj.sites[0];

Try it Yourself »

Looping Through Arrays

You can use for-in to access arrays:

Example

for (i in myObj.sites) { x += myObj.sites[i] + "<br>"; }

Try it Yourself »

You can also use a for loop:

Example

for (i = 0; i < myObj.sites.length; i++) { x += myObj.sites[i] + "<br>"; }

Try it Yourself »

Arrays in Nested JSON Objects

Arrays in JSON objects can contain another array, or another JSON object:

Example

myObj = { "name":"Websites", "num":3, "sites": [ { "name":"Google", "info":[ "Android", "Google Search", "Google Translate" ] }, { "name":"Example", "info":[ "Example Tutorial", "Example Tools", "Example WeChat" ] }, { "name":"Taobao", "info":[ "Taobao", "Online Shopping" ] } ] }

We can use for-in to loop 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>"; } }

Try it Yourself »

Modify Array Values

You can use index values to modify array values:

Example

myObj.sites[1] = "Github";

Try it Yourself »

Delete Array Elements

We can use thedeletekeyword to delete array elements:

Example

delete myObj.sites[1];

Try it Yourself »
Other Extensions