JSON Array

As an array of a JSON object

Example

[  "Porsche", "BMW", "Volvo" ]

JSON arrays are almost the same as JavaScript arrays.

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

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

Arrays in JSON objects

An array can be the value of an object property:

Example

{
"name":"Bill Gates",
"age":62,
"cars":[ "Porsche", "BMW", "Volvo" ]
}

Accessing array values

You can access array values using

Example

x = myObj.cars[0];

Try It Yourself

to traverse an array

You can use for-in Loops to access array values:

Example

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

Try It Yourself

Or you can use for Loop:

Example

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

Try It Yourself

Nested arrays in JSON objects

The values in an array can also be another array, or even another JSON object:

Example

myObj =  {
   "name":"Bill Gates",
   "age":62,
   "cars": [
	  {"name":"Porsche",  "models":[ "911", "Taycan" ]},
	  {"name":"BMW", "models":[ "M5", "M3", "X5" ]},
	  {"name":"Volvo", "models":[ "XC60", "V60" ]}
   ]
}

To access arrays within an array, use a for-in loop for each array:

Example

for (i in myObj.cars) {
    x += "<h1>" + myObj.cars[i].name  + "</h1>";
    for (j in myObj.cars[i].models) {
         x += myObj.cars[i].models[j];
    }
}

Try It Yourself

Modify Array Value

Please use the index number to modify the array:

Example

myObj.cars[1] = "Mercedes Benz";

Try It Yourself

Delete Array Item

Please use delete Use keywords to delete items from an array:

Example

delete myObj.cars[1];

Try It Yourself