When should we use JSON.encode() and when JSON.stringify()

ServiceNow Use6
Tera Guru

Hi,

I just wanted to know under what circumstances we use encode() and stringify() in scriptIncludes? I blindly use the alternative when the other doesn't work without knowing the actual reason. Kindly help.

Regards

Suman P.

3 REPLIES 3

Mohammad Danis1
Giga Guru

Hi @ServiceNow Use6 ,

Please find the answers:

1. JSON.encode() in ServiceNow
Purpose: Converts a JavaScript object into a JSON string.
Usage: Specifically designed for use in ServiceNow's server-side scripting (e.g., Business Rules, Script Includes, etc.).
Why Use It: ServiceNow provides JSON.encode() as part of its Glide scripting API to ensure compatibility with its platform.
Example:

Copy the code
var obj = { name: "John", age: 30 };
var jsonString = JSON.encode(obj);
gs.info(jsonString); // Output: {"name":"John","age":30}

2. JSON.stringify() in JavaScript
Purpose: Converts a JavaScript object into a JSON string.
Usage: Standard JavaScript method available in both client-side and server-side environments.
Why Use It: Use this in client-side scripting (e.g., ServiceNow's Client Scripts, UI Pages, or Widgets) or when working outside ServiceNow's Glide API.
Example:

Copy the code
var obj = { name: "John", age: 30 };
var jsonString = JSON.stringify(obj);
console.log(jsonString); // Output: {"name":"John","age":30}

If my response helped please mark it correct and close the thread so that it benefits future readers.
Regards,
Mohammad Danish

Chaitanya ILCR
Kilo Patron

Hi @ServiceNow Use6 ,

 

You no longer have to use the JSON.encode() for converting objects into the strings

ServiceNow has created a script include named JSON and add a method encode which does the same work as JSON.strigify() (a Javascript method)

 

they have created that script include because the JSON.strigify was not supported in the earlier versions

 

now you can just use JSON.stringify and JSON.parse 

you don't no longer have to use JSON.encode and decode

 

 

Please mark my answer as helpful/correct if it resolves your query.

Regards,
Chaitanya

Ankur Bawiskar
Tera Patron
Tera Patron

@ServiceNow Use6 

both are doing the same thing. converting javascript object into a JSON string.

Most widely JSON.stringify() is used.

If my response helped please mark it correct and close the thread so that it benefits future readers.

Regards,
Ankur
✨ Certified Technical Architect  ||  ✨ 9x ServiceNow MVP  ||  ✨ ServiceNow Community Leader