Search code examples
javascriptservicenow

Trying to parse and access the item in a JSON object


I am trying to parse and access the item in a JSON object. How can I access the 'entity' array in my JSON payload?

var results = {"id": "92-4dac-4307-9038-c50e829a022a","funa": ["4667"],"entity": [{"id":"98","en": "com","type": "AAF"},{"id":"99","en": "com","type": "AAF"}]};
gs.log(">> raw result: " + results.funa);    //output : 4667
var str = JSON.stringify(results);
var parser = new JSONParser();
results = parser.parse(str);
gs.log(" >> after parse mots: " + results.funa);  //output : 4667
gs.log(" >> after parse id0: " + results.entity.length);  //output : 2

for (var key in results)
    gs.log("Key is: " + key + " and value is: " + results.entity[key]);   //undefined

Solution

  • This question is tagged with "ServiceNow" and none of the previous answers are sensitive to the nuances of ServiceNow's Rhino engine. ES6 syntax will throw the following error in any server-side script Javascript compiler exception: syntax error. At present (Jan. 2022), ServiceNow only supports ES5 JavaScript.

    You should use ServiceNow's JSON wrapper for parsing and stringifying your objects. The JSON wrapper code lives in a Script Include called JSON which you can peruse.

    Several ES5 methods are available to you - including the forEach() method. Because entity is an array, we use forEach() to iterate over the entity array of objects. Note that this is only one of several ways to iterate over this array.

    I've updated your code snippet and added comments to reflect the answer to your question.

    var results = {
        "id": "92-4dac-4307-9038-c50e829a022a",
        "funa": ["4667"],
        "entity": [
            {"id":"98","en": "com","type": "AAF"},
            {"id":"99","en": "com","type": "AAF"}
        ]};
    
    gs.info(">> raw result: " + results.funa[0]); // output : 4667
    
    var resultsStr = global.JSON.stringify(results); // Convert result to string
    
    var resultsObj = global.JSON.parse(resultsStr); // Convert resultStr to an object
    
    gs.info(" >> after parse mots: " + resultsObj.funa[0]);  // output : 4667
    gs.info(" >> after parse id0: " + resultsObj.entity.length);  //output : 2
    
    resultsObj.entity.forEach(function(entity) { // Use forEach() to iterate through each obj in the entity array
            for (var key in entity) { // Iterate through each key in the current array element
                 gs.info("Key is: " + key + " and value is: " + entity[key]); // Access entity array element value from the parsed resultsObj 
            }
        });