Skip to main content

JSON Array Literals

JSON array represents ordered list of values.

JSON array can store multiple values.

It can store string, number, boolean or object in JSON array.

In JSON array, values must be separated by comma.

Example of JSON string containing a JSON array literal:

'["Ford", "BMW", "Fiat"]'

In JSON, array values must be of type string, number, object, array, boolean or null.

In JavaScript, array values can be all of the above, plus any other valid JavaScript expression, including functions, dates, and undefined.

JSON Array Literal of Strings

The string values must be enclosed within double quote and comma-separated.

["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]

JSON Array Literal of Numbers

Numbers must me comma-separated.

[12, 34, 56, 43, 95]

JSON Array Literal of Booleans

Booleans must me comma-separated.

[true, true, false, false, true]

JSON Array Literal of Objects

{
"employees":[
{"name":"Tom", "email":"[email protected]"},
{"name":"John", "email":"[email protected]"},
{"name":"Logan", "email":"[email protected]"},
{"name":"Ryan", "email":"[email protected]"}
]
}

JSON Multidimensional Array

It is an array of arrays.

[    
[ "a", "b", "c" ],
[ "d", "e", "f" ],
[ "g", "h", "i" ]
]

Convert JSON Array Literal to JavaScript Array

You can create a JavaScript array from a literal:

let myArray = ["Ford", "BMW", "Fiat"];

You can create a JavaScript array by parsing a JSON string:

let myJSON = '["Ford", "BMW", "Fiat"]';  
let myArray = JSON.Parse(myJSON);

Accessing Array Values

You access array values by index:

let value = myArray[0];

Arrays in Objects

Objects can contain arrays:

{  
"name":"Tom",
"surname":"Smith",
"cars":["Ford", "BMW", "Fiat"]
}

You access array values by index:

myObj.cars[0];

Looping Through an Array

You can access array values by using a for in loop:

for (let i in myObj.cars) {  
x += myObj.cars[i];
}

Or you can use a for loop:

for (let i = 0; i < myObj.cars.length; i++) {  
x += myObj.cars[i];
}