How can I create a dynamic request body with sub-properties?

Hi,

I found this video from another topic, however, the video did not answer how to create sub-properties.

This is my request body

{
    "businessName": "{{$randomCompanyName}}",
    "contact": {
        "prefix": "{{$randomNamePrefix}}",
        "name": "{{$randomFirstName}}",
        "gender": "{{randomSex}}",
        "dob": "{{pastdate}}",
    },
    "address": {
        "address": "{{$randomStreetAddress}}",
        "city": "{{$randomCity}}",
        "state": "{{randomUSState}}",
        "zipCode": "{{randomZipCode}}",
    }
}

I would love to generate the request body dynamically. In my pre-req, I started with the following:

const body = {}
body.businessName = "{{$randomCompanyName}}"
body.contact.append("prefix": "{{$randomNamePrefix}}")
if (flipCoin()) {
    body.contact.append("name": "{{$randomFirstName}}")
}
if (flipCoin()) {
    body.contact.append("gender": "{{randomSex}}")
}
pm.environment.set("request", JSON.stringify(body));

I just cannot figure out a way to append the parameter, “name” to the next item in body.contact.

First thing to mention is that is not how you use dynamic varibles in scripts.

To use dynamic variables in pre-request or post-response scripts, you need to use pm.variables.replaceIn(), for example pm.variables.replaceIn('{{$randomFirstName}}').

Not sure why you need append here. Body is a variable, and you should just be able to add the name to the object, the same way you did the business name on the second line.

As contact is an object, you will need to create that first.

I would create the scaffold for the entire object, and then only use extra code for the flipCoin() elements.

let body = {
    "businessName": pm.variables.replaceIn('{{$randomCompanyName}}'),
    "contact": {
        "prefix": pm.variables.replaceIn('{{$randomNamePrefix}}'),
        "dob": pm.variables.replaceIn('{{$pastdate}}'),
    },
    "address": {
        "address": pm.variables.replaceIn('{{$randomStreetAddress}}'),
        "city": pm.variables.replaceIn('{{$randomCity}}'),
        "state": pm.variables.replaceIn('{{$randomUSState}}'), 
        "zipCode": pm.variables.replaceIn('{{$randomZipCode}}')
    }
}

body.contact.name = pm.variables.replaceIn('{{$randomFirstName}}');

pm.request.body.raw = body;

Some of your variables aren’t available though.

This is the variable list.

It doesn’t include past date, random US state or random zip code.

Thank you! That is a great idea to build the scaffold of the object first.

Plus, I implemented past date, random US state, and random zip code, so those variables work in my collection.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.