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

dpalmer
Kilo Guru

Hello Rako, Try returning the object without parsing it.



Try running this in an index.html file and check the console output:          


                      var results = {};


                        var valObj = {


                      test1: "test",


                      test2: "test2"


              };


              results["firstObj"] = valObj;


              console.log(results["firstObj"]);


       


I have to access my developer instance to test it out for a more thorough answer and examples but try looking at the below link.


Stack overflow has a nice link for this same issue as well I believe. javascript - Parsing JSON giving "unexpected token o" error - Stack Overflow


"Your data is already an object. No need to parse it. The javascript interpreter has already parsed it for you."


That is an interesting idea. I am not getting an exception though. Removing the parse step does log to the console correctly, but still no data on the attributes. I would definitely be open to further details if you have them.


Try this...Client Script On Table.PNGScript Include.PNGConsole Log of Object.PNG


This is very helpful. My script is different in a couple ways - 1) It is not client-callable, and 2) it is loaded via a UI Macro and is compiled in the <g:evaluate> script. That said, your screenshots show that it works as client-callable, so I will probably go that direction. Thank you for taking the time to set this up.