How to Validate Mandatory JSON Fields in a ServiceNow Widget
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
2 hours ago - last edited 2 hours ago
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
39m ago
Hello @JVINAY ,
In this line :
var taskGR = new GlideRecord('u_cloud_intake_task');
...
taskGR.query();
> The more better than looping through all tasks and checking in script, the filter happens at the DB query level.
var taskGR = new GlideRecord('u_cloud_intake_task');
taskGR.addQuery('u_cloud_task_type', 'provision');
taskGR.addQuery('u_intake.cmdb_ci_business_app', input.apmSysId); // dot-walk filter
taskGR.orderByDesc('sys_created_on');
taskGR.setLimit(1); // only need the most recent matching task
taskGR.query();
> Also your validation checks:
if (!jsonData.apm_id) jsonMessages.push('APM ID missing');
if (!jsonData.namespace_name) jsonMessages.push('Namespace Name missing');But your sample JSON has apm:APM1082819, not apm_id. And there's no namespace_name key at all in the example you shared.
Try this code :
// Central Intake JSON Validation
var jsonReady = false;
var jsonMessages = [];
var taskGR = new GlideRecord('u_cloud_intake_task');
taskGR.addQuery('u_cloud_task_type', 'provision');
taskGR.addQuery('u_intake.cmdb_ci_business_app', input.apmSysId);
taskGR.orderByDesc('sys_created_on');
taskGR.setLimit(1);
taskGR.query();
if (taskGR.next()) {
var jsonText = taskGR.getValue('u_namespace_request_schema');
if (!jsonText) {
jsonMessages.push('No JSON payload found on Intake Task ' + taskGR.number);
} else {
try {
var jsonData = JSON.parse(jsonText);
if (!jsonData.apm)
jsonMessages.push('APM ID missing');
if (!jsonData.cir_request_id)
jsonMessages.push('CIR Request ID missing');
if (!jsonData.car_intake_id)
jsonMessages.push('Cloud Intake ID missing');
if (!jsonData.application_name)
jsonMessages.push('Application Name missing');
// Confirm whether namespace_name is a required key in the real schema
// if (!jsonData.namespace_name)
// jsonMessages.push('Namespace Name missing');
jsonReady = (jsonMessages.length === 0);
} catch (e) {
jsonReady = false;
jsonMessages.push('Parse Error: ' + e.message);
}
}
} else {
jsonMessages.push('No Intake Task found for selected Business Application');
}
data.jsonResult = jsonReady ? 'READY' : 'NOT READY';
data.jsonMessages = jsonMessages;
data.jsonSummary = jsonReady
? 'Validated key JSON attributes successfully.'
: jsonMessages.join(', ');
If my response helped mark as helpful and accept the solution.
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
37m ago
did you take help of any AI tool like co-pilot etc and check what suggestion it gave to fix this?
Ankur
✨ Certified Technical Architect || ✨ 10x ServiceNow MVP || ✨ ServiceNow Community Leader