The CreatorCon Call for Content is officially open! Get started here.

Parse and get json value for any unique key in json object

Ankur Bawiskar
Tera Patron
Tera Patron

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:

AnkurBawiskar_0-1730782500623.png

 

Regards,
Ankur
Certified Technical Architect  ||  9x ServiceNow MVP  ||  ServiceNow Community Leader
0 REPLIES 0