How to access the value of a property in a JSON object?
To access the property values of a JSON object, you can use either a dot notation or square brackets to access the properties.
For example, let’s say we have the following JSON object:
{
"name": "John",
"age": 30,
"city": "New York"
}
To obtain the value of the name attribute, you can use the following method:
- The name property of the jsonObject.
- the key “name” in the jsonObject
Example code:
let jsonObject = {
"name": "John",
"age": 30,
"city": "New York"
};
console.log(jsonObject.name); // 输出: John
console.log(jsonObject["name"]); // 输出: John
Both dot and bracket notation can be used to access properties of a JSON object. However, the advantage of using bracket notation is the ability to use variables or dynamic expressions as property names. For example:
let propertyName = "name";
console.log(jsonObject[propertyName]); // 输出: John
This allows for dynamically retrieving the value of a property based on the value of a variable.