Reputation: 2737
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
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
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