Skip to content

Commit 26a2502

Browse files
authored
Fetch JSON Object (#1506)
* Create script.js * Update script.js The script fetches a JSON object containing specified field values from a GlideRecord instance in ServiceNow. * Create readme.md
1 parent 71f93db commit 26a2502

File tree

2 files changed

+32
-0
lines changed

2 files changed

+32
-0
lines changed

Server Side/FetchJSONObject/readme.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
The `fetchJSONObject` function is designed to retrieve a JSON object containing specified field values from a GlideRecord instance in ServiceNow.
2+
It allows for optional input of field names to fetch; if no fields are specified, all fields will be retrieved.

Server Side/FetchJSONObject/script.js

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
function fetchJSONObject(gr, desiredFields /* optional */) {
2+
// Ensure this is a valid GlideRecord
3+
if (!(gr instanceof GlideRecord) || !gr.isValidRecord()) {
4+
return {};
5+
}
6+
7+
// Determine fields to retrieve; if none specified, get all fields
8+
if (!Array.isArray(desiredFields) || desiredFields.length === 0) {
9+
var gRU = new GlideRecordUtil();
10+
desiredFields = gRU.getFields(gr); // Retrieves all field names for the record
11+
}
12+
13+
var fieldValues = {};
14+
// Use forEach to loop through the desired fields and add their values to the JSON object
15+
desiredFields.forEach(function(fieldName) {
16+
if (gr.isValidField(fieldName)) { // Ensure the field exists in the GlideRecord
17+
var fieldValue = gr.getValue(fieldName);
18+
fieldValues[fieldName] = fieldValue ? fieldValue : ''; // Use empty string if value is null
19+
}
20+
});
21+
22+
return fieldValues;
23+
}
24+
25+
// Usage example:
26+
//var gr = new GlideRecord('incident');
27+
//gr.get('sys_id'); // Replace with an actual sys_id or use query methods to get a record
28+
//var jsonObject = fetchJSONObject(gr); // Optionally, add an array of specific fields as the second argument
29+
//gs.info(JSON.stringify(jsonObject)); // Logs the JSON object
30+

0 commit comments

Comments
 (0)