- 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.
For example –
{ "name" : "Admin", "age" : 36, "rights" : [ "admin", "editor", "contributor" ] }
Access object values
You can access object values in two ways :
1) Using dot (.) notation
var author = { "name" : "Admin", "age" : 36, "rights" : [ "admin", "editor", "contributor" ] } console.log( author.name ); //Output Admin
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
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" ] } for (x in author) { console.log(x + " - " + (author[x])); } //Output name - Admin age - 36 rights - admin,editor,contributor
Modify object values
To modify object values, use any of given two ways:
1) Using dot (.) notation
var author = { "name" : "Admin", "age" : 36, "rights" : [ "admin", "editor", "contributor" ] } author.name = "Lokesh"; console.log( author.name ); //Output Lokesh
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
Delete object values
Use the delete
keyword to delete properties from a JSON object:
delete author.name;
Leave a Reply