JSON Object

The JSON object data type is a list of name-value pairs surrounded in curly braces.

  1. JSON objects are very much like javascript objects.
  2. JSON objects are written in key/value pairs.
  3. JSON objects are surrounded by curly braces { }.
  4. Keys must be strings, and values must be a valid JSON data type (string, number, object, array, boolean or null).
  5. Keys and values are separated by a colon.
  6. Each key/value pair is separated by a comma.

A JSON object example is:

{
	"name" : "Admin",
	"age" : 36,
	"rights" : [ "admin", "editor", "contributor" ]
}

1. Access object values

You can access object values in two ways :

1.1. Using dot (.) notation

var author = {
	"name" : "Admin",
	"age" : 36,
	"rights" : [ "admin", "editor", "contributor" ]
}

console.log( author.name );

//Output

Admin

1.2. Using bracket ([]) notation

var author = {
	"name" : "Admin",
	"age" : 36,
	"rights" : [ "admin", "editor", "contributor" ]
}

console.log( author [ "name" ] );
console.log( author [ "age" ] );

//Output

Admin
36

2. Looping object values

You can loop through object values using for loop, just like looping through an array.

var author = {
	"name" : "Admin",
	"age" : 36,
	"rights" : [ "admin", "editor", "contributor" ]
}

//Looping

for (x in author)
{
	console.log(x + " - " + (author[x]));
}

//Output

name - Admin
age - 36
rights - admin,editor,contributor

3. Modify object values

To modify object values, use any of the given two ways:

3.1. Using dot (.) notation

var author = {
	"name" : "Admin",
	"age" : 36,
	"rights" : [ "admin", "editor", "contributor" ]
}

author.name = "Lokesh";

console.log( author.name );

//Output

Lokesh

3.2. Using bracket ([]) notation

var author = {
	"name" : "Admin",
	"age" : 36,
	"rights" : [ "admin", "editor", "contributor" ]
}

author["name"] = "Lokesh";
author["age"] = 35;

console.log( author [ "name" ] );
console.log( author [ "age" ] );

//Output

Lokesh
35

4. Delete object values

Use the delete keyword to delete properties from a JSON object:

delete author.name;

Was this article helpful?

Comments

  1. Regarding “Delete object values”
    I’m going to guess that you can delete object properties using the ([]) bracket notation, as well as using the dot (.) notation?

    Reply

Leave a Comment