Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

JSON Arrays

JSON Arrays


Arrays as JSON objects

Example

[

"

Google

"

,

"

Runoob

"

,

"

Taobao

"

]

A JSON array is written in square brackets.

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

In JSON, array values must be valid JSON data types (string, number, object, array, boolean, or null).

In JavaScript, array values can be the JSON data types above, or JavaScript expressions, including functions, dates, and undefined.


Arrays in JSON objects

The value of an object property can be an array:

Example

{

"

name

"

:

"

Website

"

,

"

num

"

:

3

,

"

sites

"

:

[

"

Google

"

,

"

Runoob

"

,

"

Taobao

"

]

}

We can use the index value to access the array:

Example

x

=

myObj

.

sites

[

0

]

;

Try it »


Looping through an array

You can use for-in to access the array:

Example

for

(

i

in

myObj

.

sites

)

{

x

+=

myObj

.

sites

[

i

]

"


"

;

}

Try it »

You can also use a for loop:

Example

for

(

i

=

0

;

i

<

myObj

.

sites

.

length

;

i

++

)

{

x

+=

myObj

.

sites

[

i

]

"


"

;

}

Try it »


Arrays in nested JSON objects

An array in a JSON object can contain another array, or another JSON object:

Example

myObj

=

{

"

name

"

:

"

Website

"

,

"

num

"

:

3

,

"

sites

"

:

[

{

"

name

"

:

"

Google

"

,

"

info

"

:

[

"

Android

"

,

"

Google Search

"

,

"

Google Translate

"

]

}

,

{

"

name

"

:

"

Runoob

"

,

"

info

"

:

[

"

Runoob Tutorial

"

,

"

Runoob Tools

"

,

"

Runoob WeChat

"

]

}

,

{

"

name

"

:

"

Taobao

"

,

"

info

"

:

[

"

Taobao

"

,

"

Online shopping

"

]

}

]

}

We can use for-in to loop through each array:

Example

for

(

i

in

myObj

.

sites

)

{

x

+=

"

"

myObj

.

sites

[

i

]

.

name

"

"

;

for

(

j

in

myObj

.

sites

[

i

]

.

info

)

{

x

+=

myObj

.

sites

[

i

]

.

info

[

j

]

"


"

;

}

}

Try it »


Modifying array values

You can use the index value to modify an array value:

Example

myObj

.

sites

[

1

]

=

"

Github

"

;

Try it »


Deleting array elements

We can use the delete The keyword to delete array elements:

Example

delete

myObj

.

sites

[

1

]

;

Try it »