javascriptibm-datapowerapic

Javascript dot notation to retrieve certain element on an object


On IBM API Connect's GatewayScript, I'm trying to write a JS script to get object value from the following request payload:

{"number": "1234",
"type": "type1",
"someKey": "SomeValue"}

I'm using the following code, but getting a NULL:

var apim = require('apim');
var RequestBody = apim.getvariable('request.body');
var result = RequestBody.number;

apim.setvariable('message.body', result);

On APIC's gatewayscript, it's essentially doing a dot notation to get that key/value ("someVal": "1234"), but it's turning out to be NULL... When I try to get the "var result" I do get all the payload... I just cannot get 1 of the value from the object where key is number = 1234.

Anyone have any ideas?

P.s. what I'm really asking is, if I wanted to get the output value of "1234" from request below:

var RequestBody = {"someVal": "1234"}

I think I would just to a dot notation of RequestBody.someVal, yes?

Thank you.


Solution

  • The code looks ok but you might have two issues...

    First check that the Request Body actually is posted correctly and that the JSON is what you expect.

    Secondly check that the Request Body is in fact JSON and not String. You can do this by:

    const requestBody = apim.getvariable('request.body');
    const jsonBody = typeof requestBody === 'string' ? JSON.parse(requestBody) : requestBody;
    
    const result = jsonBody.number;