Return complex JSON object from Script Include

rako
Kilo Expert

I am having a bit of trouble returning a JSON object of objects.

The object is creating correctly, and the attributes are creating correctly, but there are no values on the attributes.

var results = {};

var valObj = {test1: "test", test2: "test2"};

results["firstObj"] = valObj;

gs.info(results["firstObj"]["test1"]) --> LOGS CORRECTLY "test"

return new global.JSON().encode(results); --> Returns {firstObj: {test1: Object, test2: Object}} --> no data

Parsed with JSON.parse(resultObj) via JS

Also tried

valObj.toString(); before encoding

global.JSON.stringify(results);

If I add another attribute with an array, then the data is returned as expected-

var results = {};

var valObj = {test3: [{working: "working"]};

results["firstObj"] = valObj;

new global.JSON().encode(results); --> Returns {firstObj: {test3: [{working: "working"}]}

What am I missing here?

1 ACCEPTED SOLUTION

8 REPLIES 8

harishdasari
Tera Guru

Hi,



https://fruitionpartners.eu/blog/2015/11/17/glideajax-return-multiple-values-using-json/



Go through this URL, it will be easy to parse in JSON




Thanks


This link includes "Simple Object", "Simple Array", and "Array of Objects" and does not cover a nested object.


Ankur Bawiskar
Tera Patron
Tera Patron

Hi Rako,



Although you are sending the complex json from script include are you able to correctly parse the value in client side with proper function.


Following script is client side which gives the desired and correct value



Script:


var str = '{"firstObj":{"test1":"test","test2":"test2"}}'; // this value will be coming from script include from answer variable



var parser = JSON.parse(str);


console.log(parser.firstObj.test2); // prints test2


console.log(parser.firstObj.test1); // prints test




Mark Correct if this solves your issue and also hit Like and Helpful if you find my response worthy based on the impact.


Thanks


Ankur


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

Thank you for the script. This is exactly what is not working. The attributes test1 and test2 have no data in them. My actual attributes are named "Module" and "Table". See parsed object that is logged to the browser console -




SNOW_Nested_JSON_Response.png