'How to access a deeply nested JSON property?
I have an object that contains HEX color code coming from API. I am storing it as an app in a vuejs app. Example, const app = {"theme":"{\"color\":\"#186DFFF0\"}"}. Whenever I am trying to access the color property by app.theme.color, I get undefined. When I am doing JSON.parse(app) I am getting Unexpected token # in JSON at position 1. Any help on how to get that HEX code and store it in a variable?
const app = {"theme":"{\"color\":\"#186DFFF0\"}"}
console.log(app.theme.color)
Solution 1:[1]
You need to parse the nested property as well.
const app = {"theme":"{\"color\":\"#186DFFF0\"}"}
const { theme } = app;
const themeParsed = JSON.parse(theme);
console.log(themeParsed.color)
This is a pretty unusual structure. I'd suggest changing whatever generates it to have the theme value be a plain object, rather than a string.
Solution 2:[2]
const app = {"theme":"{\"color\":\"#186DFFF0\"}"};
const jsonString = app?.theme;
// returns json string => "{\"color\":\"#186DFFF0\"}"
const object = JSON.parse(jsonString);
// returns object => { color: "#186DFFF0" }
// Get nested color property
const color = object?.color;
// returns string => "#186DFFF0"
// if property "color" doesn't exist in object it gives undefined
console.log(color);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | CertainPerformance |
| Solution 2 |
