Parse and get json value for any unique key in json object
New article articles in ServiceNow Community
·
Dec 11, 2024
·
article
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:
View original source
https://www.servicenow.com/community/workflow-automation-articles/parse-and-get-json-value-for-any-unique-key-in-json-object/ta-p/3124770
Ankur Bawiskar