Parse and get json value for any unique key in json object
Options
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
11-04-2024 08:55 PM
This is a simple function which can be called to fetch value for any unique key in simple or complex json object.
Example:
var obj = {"name":"Chris","age":23,"address":{"city":"New York","country":"America"},"friends":[{"name":"Emily","hobbies":["biking","music","gaming"]},{"name":"John","hobbies":["soccer","gaming"]}]};
var val = getKeyValue(obj, 'city');
gs.info(val);
// this function takes the complete json object and the unique key whose value needs to be fetched
function getKeyValue(obj, key){
try {
if (obj.hasOwnProperty(key)) {
return obj[key];
}
for (var k in obj) {
if (typeof obj[k] === 'object' && obj[k] !== null) {
var result = this.getKeyValue(obj[k], key);
if (result !== undefined) {
return result;
}
}
}
return undefined;
} catch (ex) {
gs.info("Exception in function getKeyValue " + ex);
}
}
Output:
Regards,
Ankur
✨ Certified Technical Architect || ✨ 9x ServiceNow MVP || ✨ ServiceNow Community Leader
Ankur
✨ Certified Technical Architect || ✨ 9x ServiceNow MVP || ✨ ServiceNow Community Leader
- 221 Views
0 REPLIES 0