Parsing JSON with scripted REST API

JJG_SNOW
Mega Guru

I have a scripted REST API from which I am attempting to parse JSON.

Unfortunately when try to log the variables, I am getting an undefined value.

What am I missing?

 

Scripted REST API:

 

 

var requestBody = request.body.dataString;
var parsedData = JSON.parse(requestBody);
var poNum = parsedData.purchaseOrderDetails.purchaseOrderNumber;
gs.info("poNum: " + poNum);

 

 

JSON being sent to endpoint:

 

{
   "purchaseOrderDetails":[
      {
         "purchaseOrderNumber":"DO 5600 24081313331"
      }
   ]
}

 

 

Result in the logs:

 

poNum: undefined

 

 

1 ACCEPTED SOLUTION

JJG_SNOW
Mega Guru

Solution:

 

var requestBody = request.body.data;
var strJSON = JSON.stringify(requestBody);
var parsedJSON = new JSONParser();
var parsed = parsedJSON.parse(strJSON);
var poNum = parsed.purchaseOrderDetails[0].purchaseOrderNumber;
gs.info("poNum: " + poNum);

View solution in original post

2 REPLIES 2

Hemanth M1
Giga Sage
Giga Sage

Hi @JJG_SNOW ,

 

Try this purchaseOrderDetails is array of object, first you need to access the array and then object attributes

var requestBody = request.body.dataString;
var parsedData = JSON.parse(requestBody);
var poNum = parsedData.purchaseOrderDetails[0]['purchaseOrderNumber'];
gs.info("poNum: " + poNum);

 

Hope this helps!!!

 

Accept and hit Helpful if it helps.

Thank you,
Hemanth
Certified Technical Architect (CTA), ServiceNow MVP 2024, 2025

JJG_SNOW
Mega Guru

Solution:

 

var requestBody = request.body.data;
var strJSON = JSON.stringify(requestBody);
var parsedJSON = new JSONParser();
var parsed = parsedJSON.parse(strJSON);
var poNum = parsed.purchaseOrderDetails[0].purchaseOrderNumber;
gs.info("poNum: " + poNum);