JSON Object
Syntax
Example:1
{ "name": "Johnson", "age": 28, "site": null }
JSON objects are written using curly braces {…}. They can contain multiple key/value pairs.
Keys must be strings, while values can be any valid JSON data type (string, number, object, array, boolean, or null). Keys and values are separated by colons (:), and each key/value pair is separated by commas (,).
Accessing Object Values
You can use dot (.
) notation to access object values:1
2
3var teacher = { "name": "Johnson", "age": 28, "site": null };
var x = teacher.name;
console.log(x); // Output: Johnson
Alternatively, you can use square brackets ([]
):1
2
3var teacher = { "name": "Johnson", "age": 28, "site": null };
var x = teacher["name"];
console.log(x); // Output: Johnson
Looping Through Objects
Use a for…in loop to iterate over object properties:1
2
3
4
5
6
7
8var teacher = { "name": "Johnson", "age": 28, "site": null };
for (var x in teacher) {
console.log(x);
}
// Output:
// name
// age
// site
To access property values while looping, use square brackets:1
2
3
4
5
6
7
8var teacher = { "name": "Johnson", "age": 28, "site": null };
for (var x in teacher) {
console.log(teacher[x]);
}
// Output:
// Johnson
// 28
// null
Nested JSON Objects
JSON objects can contain other JSON objects:1
2
3
4
5
6
7
8
9var teacher = {
"name": "Johnson",
"age": 28,
"site": {
"site1": "www.linjiangxiong.com",
"site2": "m.linjiangxiong.com",
"site3": "blog.linjiangxiong.com"
}
};
Access nested objects using dot notation or square brackets:1
2
3var x = teacher.site.site1;
// or
var x = teacher.site["site1"];
Executing console.log(x);
will output www.linjiangxiong.com
.
Modifying Values
Use dot notation or square brackets to modify JSON object values:1
2
3teacher.site.site1 = "https://www.linjiangxiong.com/";
// or
teacher.site["site1"] = "https://www.linjiangxiong.com/";
Deleting Object Properties
Use the delete
keyword to remove JSON object properties:1
2
3delete teacher.site.site1;
// or
delete teacher.site["site1"];
For example, perform the following code.1
2
3
4
5
6
7
8
9
10
11
12
13var teacher = {
"name": "Johnson",
"age": 28,
"site": {
"site1": "www.linjiangxiong.com",
"site2": "m.linjiangxiong.com",
"site3": "blog.linjiangxiong.com"
}
};
delete teacher.site.site1;
console.log(teacher);
The output will be:1
2
3
4
5
6
7
8{
"name": "Johnson",
"age": 28,
"site": {
"site2": "m.linjiangxiong.com",
"site3": "blog.linjiangxiong.com"
}
}