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


Smartphone icons created by Freepik - Flaticon

  • 18.7 JSON Objects

    This is a JSON string:

    '{"name":"John", "age":30, "car":null}'

    Inside the JSON string there is a JSON object literal:

    {"name":"John", "age":30, "car":null}
    • JSON object literals are surrounded by curly braces {}.
    • JSON object literals contains key/value pairs.
    • Keys and values are separated by a colon.
    • Keys must be strings, and values must be a valid JSON data type:
      • string
      • number
      • object
      • array
      • boolean
      • null
    • Each key/value pair is separated by a comma.
    • It is a common mistake to call a JSON object literal "a JSON object".
    • JSON cannot be an object. JSON is a string format.
    • The data is only JSON when it is in a string format. When it is converted to a JavaScript variable, it becomes a JavaScript object.

    JavaScript Objects

    You can create a JavaScript object from a JSON object literal:

    Example 1: JSON Objects - Creating an Object from a JSON Literal part 1
    myObj = {"name":"John", "age":30, "car":null};

    Normally, you create a JavaScript object by parsing a JSON string:

    Example 2: JSON Objects - Creating an Object from a JSON Literal part 2
    myJSON = '{"name":"John", "age":30, "car":null}';
    myObj = JSON.parse(myJSON);

    Accessing Object Values

    You can access object values by using dot (.) notation:

    Example 3: JSON Objects - Access a JavaScript Object part 1
    const myJSON = '{"name":"John", "age":30, "car":null}';
    const myObj = JSON.parse(myJSON);
    x = myObj.name;

    You can also access object values by using bracket ([]) notation:

    Example 4: JSON Objects - Access a JavaScript Object part 2
    const myJSON = '{"name":"John", "age":30, "car":null}';
    const myObj = JSON.parse(myJSON);
    x = myObj["name"];

    Looping an Object

    You can loop through object properties with a for-in loop:

    Example 5: JSON Objects - Looping an Object part 1
    const myJSON = '{"name":"John", "age":30, "car":null}';
    const myObj = JSON.parse(myJSON);
    
    let text = "";
    for (const x in myObj) {
      text += x + ", ";
    }

    In a for-in loop, use the bracket notation to access the property values:

    Example 6: JSON Objects - Looping an Object part 2
    const myJSON = '{"name":"John", "age":30, "car":null}';
    const myObj = JSON.parse(myJSON);
    
    let text = "";
    for (const x in myObj) {
      text += myObj[x] + ", ";
    }
    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