The JSON object data type is a list of name-value pairs surrounded in curly braces.
- JSON objects are very much like javascript objects.
- JSON objects are written in key/value pairs.
- JSON objects are surrounded by curly braces
{ }
. - Keys must be strings, and values must be a 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.
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;
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?