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 | var teacher = { "name": "Johnson", "age": 28, "site": null }; |
Alternatively, you can use square brackets ([]
):
1 | var teacher = { "name": "Johnson", "age": 28, "site": null }; |
Looping Through Objects
Use a for…in loop to iterate over object properties:
1 | var teacher = { "name": "Johnson", "age": 28, "site": null }; |
To access property values while looping, use square brackets:
1 | var teacher = { "name": "Johnson", "age": 28, "site": null }; |
Nested JSON Objects
JSON objects can contain other JSON objects:
1 | var teacher = { |
Access nested objects using dot notation or square brackets:
1 | 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 | teacher.site.site1 = "https://www.linjiangxiong.com/"; |
Deleting Object Properties
Use the delete
keyword to remove JSON object properties:
1 | delete teacher.site.site1; |
For example, perform the following code.
1 | var teacher = { |
The output will be:
1 | { |