ServiceNow Workflow Script not Finding Term Value in JSON

appstorm
Tera Contributor

I am using the following script in Workflow Editor to extract the value for "TERM_CODE" from JSON output in a form drop-down.  However, logs show "Extracted TERM_CODE: TERM_CODE not found."  I'm guessing this has something to do with the manner in which the JSON is being parsed.

// Get the course_information field from the requested item
var courseInfo = current.course_information;

// Initialize a variable to hold the result
var result = "";

// Log the raw course_information to verify the data
gs.info("Raw course_information: " + courseInfo);

// Parse the JSON string from course_information
var parsedInfo;

try {
    parsedInfo = JSON.parse(courseInfo);
    gs.info("Parsed course_information: " + JSON.stringify(parsedInfo));  // Log parsed JSON for inspection
} catch (e) {
    // If parsing fails, handle the error gracefully
    gs.error("Error parsing course_information JSON: " + e);
    parsedInfo = null; // Set parsedInfo to null if the parsing fails
}

// Check if the parsing was successful and TERM_CODE exists in the parsed object
if (parsedInfo && parsedInfo.TERM_CODE) {
    // Stringify the TERM_CODE value and set it as the result
    result = JSON.stringify(parsedInfo.TERM_CODE);
} else {
    // If TERM_CODE doesn't exist or parsing failed, set the result to an empty string or a default value
    result = "TERM_CODE not found";
}

// Log the result for debugging purposes
gs.info("Extracted TERM_CODE: " + result);

 

Thoughts?

1 REPLY 1

Abhay Kumar1
Giga Sage

@appstorm The issue likely stems from the structure of the JSON data in course_information. If the JSON structure is not as expected, parsedInfo.TERM_CODE will not be found, and that would cause the "TERM_CODE not found" message.

You can verify below things:

 

1. Verify the Structure of course_information: Use gs.info("Parsed course_information: " + JSON.stringify(parsedInfo));

 

I have seen this issue many times in validating/reading data in JSON:

2. Access Nested Objects or Arrays: If TERM_CODE is nested within another object or array inside parsedInfo, adjust your code to access it accordingly.

 

And last piece, JSON key names are case-sensitive. Ensure that TERM_CODE matches the exact case in your JSON.

Hope this will help you