Home > Mobile >  How to access a deeply nested JSON property?
How to access a deeply nested JSON property?

Time:02-22

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)

CodePudding user response:

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.

CodePudding user response:

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);

  • Related