Easy Tutorial
❮ Js Json Arrays Json Stringify ❯

JSON Object


Object Syntax

Example

{ "name":"tutorialpro", "alexa":10000, "site":null }

JSON objects are written within curly braces {...}.

An object can contain multiple key/value pairs.

The key must be a string, and the value can be any valid JSON data type (string, number, object, array, boolean, or null).

Keys and values are separated by a colon :.

Each key/value pair is separated by a comma ,.


Accessing Object Values

You can access the value of an object using dot notation .:

Example

var myObj, x;
myObj = { "name":"tutorialpro", "alexa":10000, "site":null };
x = myObj.name;

You can also access the value of an object using bracket notation []:

Example

var myObj, x;
myObj = { "name":"tutorialpro", "alexa":10000, "site":null };
x = myObj["name"];

Looping Through Objects

You can use a for-in loop to iterate over the properties of an object:

Example

var myObj = { "name":"tutorialpro", "alexa":10000, "site":null };
for (x in myObj) {
    document.getElementById("demo").innerHTML += x + "<br>";
}

When looping through the properties of an object with a for-in loop, use bracket notation [] to access the value of the property:

Example

var myObj = { "name":"tutorialpro", "alexa":10000, "site":null };
for (x in myObj) {
    document.getElementById("demo").innerHTML += myObj[x] + "<br>";
}

Nested JSON Objects

A JSON object can contain another JSON object:

Example

myObj = {
    "name":"tutorialpro",
    "alexa":10000,
    "sites": {
        "site1":"www.tutorialpro.org",
        "site2":"m.tutorialpro.org",
        "site3":"c.tutorialpro.org"
    }
}

You can access nested JSON objects using dot notation . or bracket notation [...].

Example

x = myObj.sites.site1;
// or
x = myObj.sites["site1"];

Modifying Values

You can modify the value of a JSON object using dot notation .:

Example

myObj.sites.site1 = "www.google.com";

You can modify the value of a JSON object using bracket notation [...]:

Example

myObj.sites["site1"] = "www.google.com";

Deleting Object Properties

You can delete properties of a JSON object using the delete keyword:

Example

delete myObj.sites.site1;

You can delete properties of a JSON object using bracket notation [...]:

Example

delete myObj.sites["site1"]
❮ Js Json Arrays Json Stringify ❯