How to dynamically add variable both key&value into json raw body of request?

Hi,
I have two variables borrowName and Seller, I need to dynamically add variable both key&value into json raw body of request,

  • case1. if borrowName is null, then I can add seller into request body.
  • case2. if seller is null, then I can add borrowName into request body.

These two variables are not fixed and need to be removed/added dynamically according to the empty value.
here is the capture,

,

I don’t know how to do this via postman pre-request script.

Any help will be greatly appreciated.

Hi @x-ray-x,

You can either use a variable to capture the entire JSON document and include something like {{dynamicPayload}} as the raw request body or you can try to make just a piece of the JSON request body dynamic. Here’s an example.

Pre-request script:

const borrowerName = pm.variables.get('borrowerName');
const seller = pm.variables.get('seller');

const key = 'borrowerNameAndSellerResolved';
if (borrowerName && borrowerName !== "null") {
    pm.variables.set(key, `,"borrowerName": "${borrowerName}"`);
} else if (seller && seller !== "null") {
    pm.variables.set(key, `,"seller": "${seller}"`);
}

Request body:

{
    "loan": {
        "productName": "product"
        {{borrowerNameAndSellerResolved}}
    }
}

Hope that helps.

Best,

Kevin

2 Likes

Hi @kevin.swiber ,
This is a really big help :muscle:, it works, thank you.


Also, does postman have a detailed script reference doc, I want to learn more about it.