Launch your tech mastery with us—your coding journey starts now!
Course Content
Advanced Java

JSON Arrays

Arrays as JSON Objects
Example

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

Arrays in JSON are almost the same as arrays in JavaScript.

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.

Arrays in JSON Objects

Arrays can be values of an object property:

Example

{
“name”:“John”,
“age”:30,
“cars”:[ “Ford”, “BMW”, “Fiat” ]
}

Accessing Array Values

You access the array values by using the index number:

Example

x = myObj.cars[0];
Looping Through an Array

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

Example

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

JSON vs XML

The following JSON and XML examples both defines an employees object, with an array of 3 employees:

JSON Example

{“employees”:[
    { “firstName”:“John”, “lastName”:“Doe” },
    { “firstName”:“Anna”, “lastName”:“Smith” },
    { “firstName”:“Peter”, “lastName”:“Jones” }
]}

XML Example

<employees>
    <employee>
        <firstName>John</firstName> <lastName>Doe</lastName>
    </employee>
    <employee>
        <firstName>Anna</firstName> <lastName>Smith</lastName>
    </employee>
    <employee>
        <firstName>Peter</firstName> <lastName>Jones</lastName>
    </employee>
</employees>