When should we use JSON.encode() and when JSON.stringify()
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎07-07-2025 01:56 AM
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.
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎07-07-2025 02:12 AM - edited ‎07-07-2025 02:15 AM
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
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎07-07-2025 02:13 AM
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
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎07-07-2025 03:49 AM
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.
Ankur
✨ Certified Technical Architect || ✨ 9x ServiceNow MVP || ✨ ServiceNow Community Leader