On the ServiceNow server, JSON.stringify converts numbers, strings and Java native objects into JSON text, and it serializes other objects through their enumerable properties or a toJSON method. A GlideElement, such as the value from current.sys_id(), has no toJSON method, so it comes out as {}. A replacer function that converts GlideElement values to strings fixes the output.
Where the JSON object comes from on the server
The JSON script include offers two sets of methods. Static methods are called on the JSON object itself, as in JSON.stringify and JSON.parse. Dynamic methods are called on an instance created with new JSON(). The platform uses the JavaScript ES5 native JSON object in place of the static methods.
The dynamic class and its encode() and decode() methods are deprecated. The JavaScript JSON object is the replacement, and new code should call it directly. A script that still depends on the old encode() and decode() behaviour can keep using those methods, but new logic should not be built on the class.
Scoped applications take a different route. Their JSON API is a set of static methods that call the same native object, and each call needs the global prefix, as in global.JSON.stringify(). If the prefix is left off, the script can fail with an error that begins with ScopedRhinoObjectWrapper and names a type that is not wrappable. When a scoped script does need the dynamic class, the constructor is written new global.JSON().
How ServiceNow server-side JSON.stringify treats each value type
The rules are narrower than many JavaScript developers expect. The table lists the cases that come up in Glide code. Each row describes what appears in the output string.
| Value passed to JSON.stringify | What appears in the output |
|---|---|
| Number or string | The primitive value, written as JSON |
| Boolean, number or string object | Converted to the matching primitive value first |
| Java native object | Converted to a string |
| Object with a toJSON method | The data that method returns |
| Other object instance | Its enumerable properties |
| Date | The same string that toISOString() returns |
| Infinity, NaN or null | null |
| GlideElement with no toJSON method | {} |
| Function, undefined or symbol inside an object | Left out |
| Function, undefined or symbol inside an array | null |
| Symbol-keyed property | Ignored, even when a replacer is passed |
Two rows need more explanation. A calculation that produces NaN or Infinity does not show up as a number in the payload. It shows up as null, so a failed calculation and a missing value look identical to the system that receives the payload.
Symbol-keyed properties are dropped whatever the replacer returns, so a replacer cannot recover them.
The enumerable rule matters for objects a script builds itself. A property defined as non-enumerable is left out, and so is a method stored on the object, because functions are omitted when they sit inside an object. Passing a bare function or undefined straight to stringify returns undefined rather than a string.
Why current.sys_id() comes back as an empty object
The usual first attempt looks like this: a script passes current.sys_id() straight into JSON.stringify so the identifier lands in a log line or an outbound payload. The output is the two-character text {}, with no identifier in it.
The reason is the type of the returned value. current.sys_id() returns a GlideElement object. GlideElement has no toJSON method, and the stringify call has nothing else to serialize from it, so the result is empty.
GlideElement is the object behind a field. Its methods are available for the fields of the current glide record, so a field read as a property, such as current.opened_by, carries the same methods and produces the same empty result when it reaches stringify unconverted. For how queries return those field objects in the first place, see the GlideRecord guide.
There are two ways out. One is to turn the Glide value into text before it reaches the stringify call. The other is to pass stringify a replacer function so that the conversion happens for each matching value inside the object. In practice the replacer is usually the tidier option when the object has many fields, because the script does not have to copy the object field by field.
A replacer function for GlideElement values
The second argument to JSON.stringify can be a replacer function. For each property it receives a name and a value, and whatever it returns is what gets written to the output. A value the replacer does not need to change is returned as it is.
The version below works from a list of property names. Each property whose name is on the list is converted with toString(), and every other value is returned unchanged.
var textFields = { opened_by: true, assigned_to: true };
function textForFields(key, value) {
if (textFields[key] === true && value !== null && value !== undefined) {
return value.toString();
}
return value;
}
var payload = global.JSON.stringify(outbound, textForFields);
The global prefix stays on the call, which is the form scoped scripts need. Without it, a scoped script can fail as described earlier.
toString() converts the field’s value to a string and returns a String, so string methods such as trim() can be chained onto the result. Once converted, the payload holds text where the object held a GlideElement.
The text itself depends on the field. The stored value of a reference field is its sys_id, while getDisplayValue() returns the display field of the referenced record. Choice fields follow the same pattern: getDisplayValue() gives a more descriptive label where the database holds a number. A payload that needs a readable name rather than an identifier should call getDisplayValue() in the replacer, because that is the method that returns the display field.
Two more methods help when blank values need handling. nil() reports whether a field is null or an empty string, which lets a script treat blank fields differently from filled ones. getDisplayValueExt() takes a second argument, the substitute text to return when the display value is null or empty, so a payload can carry a placeholder instead of an empty string.
Dates and GlideDateTime values in the payload
A JavaScript Date needs no conversion. Its toJSON method returns the same string that toISOString() returns, and stringify treats that result as a string.
A GlideDateTime is a Glide object, so it needs its text form. toString() returns the stored value in the internal format, yyyy-MM-dd HH:mm:ss, using the system time zone rather than the user’s time zone. That is the same result as getValue(). Because the system time zone is used rather than the user’s, the text does not change with the time zone of whoever runs the script. A display value from getDisplayValue() would follow the user’s time zone instead, and date fields store UTC in the database.
A new GlideDateTime() with no arguments starts at the current date and time. When a string is passed, the value is matched to the system format first, then to other formats in order.
Defining toJSON on your own objects
JSON.stringify cannot convert a user-defined object unless that object provides a toJSON method. When it does, the method decides which data is serialized. That makes toJSON the cleanest route when a script builds its own object and wants control over the output.
The pattern suits an object that holds Glide values internally but should present plain values to the outside. The wrapper below keeps a GlideRecord and returns a small plain object from toJSON.
function TicketSummary(gr) {
this.gr = gr;
}
TicketSummary.prototype.toJSON = function () {
return {
number: this.gr.getValue('number'),
assignee: this.gr.assigned_to.getDisplayValue()
};
};
var text = global.JSON.stringify(new TicketSummary(current));
Because the wrapper defines toJSON, stringify uses the object that method returns. The GlideRecord and its helper methods stay out of the output, and the GlideElement inside does not reach the stringify call directly, which removes the empty-object problem at its source. Helpers like this one are usually small script includes, and the script include guide covers how those are set up.
Reading JSON back with JSON.parse and GlideJsonPath
JSON.parse is the counterpart to stringify. It takes a JSON formatted string and builds an object or primitive value from it, which is the usual way to read a payload that came in from an integration. In a scoped script the call is written global.JSON.parse(str).
For picking values out of a larger document, GlideJsonPath is the more targeted tool. It is available by default. Its constructor takes the JSON document as a string and parses it, and its read() method takes a JSONPath expression and returns the matching JavaScript values. All valid JSONPath expressions are supported.
var doc = new GlideJsonPath('{"team":{"members":["Ana","Ben","Chloe"]}}');
var names = doc.read("$['team']['members'][*]");
The wildcard at the end of the path matches each item in the array, so the call returns three values, one for each member.
Frequently asked questions
Why does JSON.stringify return {} for current.sys_id()?
The value is a GlideElement, which has no toJSON method, and the stringify call has no other data to serialize from it. Converting the value to a string first, or passing a replacer that does the conversion, fixes the output.
Which values come out as null?
Infinity, NaN and null. A calculation that produces NaN or Infinity therefore shows up as null in the payload, not as the number the script calculated.
Can a replacer recover symbol-keyed properties?
No. Symbol-keyed properties are ignored whatever the replacer returns, so a replacer cannot bring them back.
Should new scripts use the JSON class?
No. The JSON class and its encode() and decode() methods are deprecated, and the JavaScript JSON object is the replacement that new code should call.
What text does toString() give for a GlideDateTime?
The stored value in the internal format, yyyy-MM-dd HH:mm:ss, in the system time zone, rather than the user’s time zone. That is the same result as getValue().