This site is mobile accessible. Press the "Tap Here" button to use a different font-size.


Smartphone icons created by Freepik - Flaticon

  • 18.8 JSON Arrays

    This is a JSON string:

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

    Inside the JSON string there is a JSON array literal:

    ["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.

    JavaScript Arrays

    You can create a JavaScript array from a literal:

    Example 1: JSON Arrays - Create JavaScript Arrays part 1
    myArray = ["Ford", "BMW", "Fiat"];

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

    Example 2: JSON Arrays - Create JavaScript Arrays part 2
    myJSON = '["Ford", "BMW", "Fiat"]';
    myArray = JSON.parse(myJSON);

    Accessing Array Values

    You access array values by index:

    Example 3: JSON Arrays - Accessing Array Values
    myArray[0];

    Arrays in Objects

    Objects can contain arrays:

    Example

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

    You access array values by index:

    Example 4: JSON Arrays - Accessing Array Values in Objects
    myObj.cars[0];

    Looping Through an Array

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

    Example 5: JSON Arrays - Looping Through an Array
    for (let i in myObj.cars) {
      x += myObj.cars[i];
    }
    Navigate this module

    Eventually the navigation links, above, will be replaced by these << (previous) and >> (next) buttons below.



    JavaScript icons used in the buttons provided by ICONS8.COM. Smartphone icons created by Freepik - Flaticon