JSON Arrays and Examples

JSON arrays and examples. Learn about arrays as JSON objects, access JSON arrays, modify or delete JSON items or values, etc.

Arrays as JSON Objects

For example

[ “Ford”, “BMW”, “Fiat” ]

Arrays in JSON are nearly the same as in JavaScript.

Array values in JSON:  string, number, object, array, boolean or null.

Array values in Javascript: all of the above and other valid JavaScript expression, functions, dates, and undefined.

Arrays in JSON Objects

Arrays can be values of an object property:

For example:

“cars”:[ “Ford”, “BMW”, “Fiat” ]

Access Array Values

Use the index number.

See JSON formatter to learn more.

Loop Through an Array

Use a for-in loop to access array values

For Example:

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

Or use a for loop:

For example:

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

 Nested Arrays in JSON Objects

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

For example:

myObj = {
“cars”: [
{ “name”:”Ford”, “models”:[ “Fiesta”, “Focus”, “Mustang” ] },
{ “name”:”BMW”, “models”:[ “320”, “X3”, “X5” ] },
{ “name”:”Fiat”, “models”:[ “500”, “Panda” ] }

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

For 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];

Modify Array Values

Use the index number to modify an array:

Delete Array Items

Use the delete keyword to delete items from an array


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s