Join the #BuildWithBuildAgent Challenge! Get recognized, earn exclusive swag, and inspire the ServiceNow Community with what you can build using Build Agent.  Join the Challenge.

unable to read the postman data properly using scripted rest api

Rama26
Tera Contributor

below is the data i have in postman

{

"info": [
{
"minimumvalue": "1",
"desiredValue": "2",
"maximumValue": "3",
},
{
"minimumvalue": "4",
"desiredNodes": "5",
"maximumNodes": "6",
}
]

} for getting these values i written the script in scripted rest api but it's not working

   var details = request.body.data;
var user_min2 = details.info[0].minimumvalue;
var user_min3 = details.info[1].minimumvalue;
When i call the endpoint received below error
{"JobsResponse":[{"status":"failure","statusMessage":"{\"error\":{\"message\":\"Cannot read property \\\"0\\\" from undefined\",\"detail\":\"TypeError: Cannot read property \\\"0\\\" from undefined (sys_ws_operation.dc44b4061b38515022078661cd4bcb36.operation_script; line 56)\"},\"status\":\"failure\"}"
8 REPLIES 8

M Ismail
Tera Guru

Hi @Rama26,

It seems the issue lies in how you're accessing the data in the script. Looking at your code, `request.body.data` suggests that you're expecting the data to be nested under a `data` property, but based on the sample JSON you provided, it's directly under the `request.body`. Here's the corrected script:


var details = request.body;
var user_min2 = details.info[0].minimumvalue;
var user_min3 = details.info[1].minimumvalue;

This script assumes that `request.body` contains the JSON data you provided directly without any nesting under a `data` property. If this is not the case and your data is indeed nested under `data`, then you would access it like this:


var details = request.body.data;
var user_min2 = details.info[0].minimumvalue;
var user_min3 = details.info[1].minimumvalue;

Please hit helpful and accept this as a solution if it solved your problem.
Thank you!

Rama26
Tera Contributor

Still receiving same error

dgarad
Giga Sage

Hi @Rama26 

please try the below code.

 

var details = request.body.data;

var jsonObject = JSON.parse(details );
var user_min1 = jsonObject.info[0].minimumvalue;
var user_min2 = jsonObject.info[1].minimumvalue;
gs.info(user_min1);
gs.info(user_min2);
If my answer finds you well, helpful, and related to the question asked. Please mark it as correct and helpful.

Thanks
dgarad

Rama26
Tera Contributor

received below error

{"JobsResponse":[{"status":"failure","statusMessage":"{\"error\":{\"message\":\"Unexpected token: o\",\"detail\":\"SyntaxError: Unexpected token: o (sys_script_include.d2426c9ec0a8016501958bf2ac79c775.script; line 155)\"},\"status\":\"failure\"}"