Read Values from JSON and JavaScript Objects
· One min read
“Reading a JSON value” usually involves two operations: parse a JSON string into a JavaScript object, then access properties on that object.
const text = '{"name":"Tom","age":18}';
const user = JSON.parse(text);
console.log(user.name);
console.log(user["age"]);
Use dot notation for fixed identifier-like names. Use brackets for dynamic or special names:
const key = "name";
console.log(user[key]);
const config = {
"user-name": "Tom",
"display name": "Tom Cat"
};
console.log(config["user-name"]);
Dynamic keys can be assembled normally:
for (let i = 1; i <= 3; i++) {
console.log(data[`r${i}`]);
}
Iterate with Object.keys, Object.values, or Object.entries:
for (const [key, value] of Object.entries(data)) {
console.log(key, value);
}
Use optional chaining when intermediate properties may be absent:
const name = result.user?.profile?.name ?? "Not set";
Only strings need JSON.parse. Many HTTP libraries already return parsed objects, and parsing them again causes an error.