blogs4t
blogs4t

Reputation: 2737

Typescript JSON How do I read JSON using hierarchical key like "appInsights:instrumentationKey"

Given the below JSON, I should be able to read the JSON using hierarchical key path such as "appInsights:instrumentationKey". How can i do this in an angular project?

{
    "appInsights": {
        "instrumentationKey": "<dev-guid-here>"
    }
},

Upvotes: 1

Views: 94

Answers (2)

ihor.eth
ihor.eth

Reputation: 2420

Is this what you are looking for ?

const obj = JSON.parse('your json');
const val1 = obj.appInsights.instrumentationKey;
const val2 = obj['appInsights'].instrumentationKey;

UPDATE: Will has fair point. If your JSON data doesnt contain user input e.g won't contain anything harmful that will execute in browser then

const val = eval('obj.' + keyPath.replace(/:/g, '.'));

or if you use Lodash: get

Upvotes: 1

Will Alexander
Will Alexander

Reputation: 3571

Something along these lines perhaps:

getJsonProperty(jsonObj, keyPath: string) {
  const keys: string[] = keyPath.split(':');
  return jsonObj[keys[0]][keys[1]];
}

If you don't know how many levels the object can have, you could write a switch statement with cases for each accepted length of the keys Array. Obviously that means hard-coding each case (and a fixed maximum number of possible levels), unless there's some other way of using string literals I'm forgetting.

Upvotes: 0

Related Questions