Creating a url encoded request using post script

Hi Everyone,
I just started using Postman some time ago. I have encountered an issue that I need some help with.

My question: I have defined an environment variable by the name of “form” whose value is
{“MD”:“someValue”,“PaReq”:“someValue”,“TermUrl”:“someUrlHere”}

I’m trying to set the three values in a new request so that it looks something like this:

I need to do this using the pre-request script as the fields in “form” are not static. I also have to post these details on a URL that I got from a previous request and declared as a variable “url”.
I’ve already tried:
const forms = JSON.parse(pm.environment.get(“form”));
pm.request.body.mode = “urlencoded”;
pm.request.body.urlencoded = forms;

But unable to define any value in the request body. Please suggest.

If you console log the body, you will see that urlencoded is an array of objects and it has a particular format.

console.log(pm.request.body.urlencoded);

image

You can replace that entire array using the following.

const form = JSON.parse(pm.environment.get("form"));
let MD = form.MD;
let PaReq = form.PaReq;
let TermUrl = form.TermUrl;

let body = [
    {
        "key": "MD",
        "value": MD
    },
    {
        "key": "PaReq",
        "value": PaReq
    },
    {
        "key": "TermUrl",
        "value": TermUrl
    }
]

pm.request.body.urlencoded = body
console.log(pm.request.body.urlencoded) 

image

@michaelderekjones Is there a way of handling this dynamically? As mentioned, the key-value pair in the form is not static.

You will need to save the object in the environment variable in the correct format.

The same as the body I posted.

[{"key":"MD","value":"someValue"},{"key":"PaReq","value":"someValue"},{"key":"TermUrl","value":"someUrlHere"}]