Marius
Marius

Reputation: 196

Adding Postman Variables in JSON Post Body inside key name fields

So i have been making my postman collections as dynamic as possible, replacing all static content that only changes slightly during different API calls into variables, to decrease workload by quite a lot.

I have one thing left that i just cannot get to work, and that is building parts of the JSON body with Variables.

Here is the outcome i want, key values on the right works just fine:

{
  "act.getEntries": {
    "act.authToken": "{{authToken}}",
    "act.resourceId": "{{activelistid}}"
  }
}

I want to make the prefix dynamic for all my json arrays, like so:

{
  "{{prefix}}.getEntries": {
    "{{prefix}}.authToken": "{{authToken}}",
    "{{prefix}}.resourceId": "{{activelistid}}"
  }
}

I cannot use JS function in the JSON body, so i am limited to only escaping (so using ""''+)

I tried doing something like this:

{
  "\"" + '{{prefix}}'.getEntries": {
    "act.authToken": "{{authToken}}",
    "act.resourceId": "{{activelistid}}"
  }
}

But in the end, that produced a request body like so:

"{

 "\"" + ""act." + ".getEntries": {

 "act.authToken": "CJvGphuWp4wXOgJq1T6Yr0e_5aU1fvs2pXFDvJPBRnw.",

 "act.resourceId": "Hp2hTKmMBABDdFhotbrvBdw=="

 }

 }"

If anyone tried this before, please let me know, or else i will just mark it as not supported.

In pre-request and post-request tests i can use proper functions so it is easy, even the URL is created from variables, but the body seems impossible..

Outside of the Body, while still limited, i can easily insert variables into strings like so:

"reference": {
      "id": "",
      "isModifiable": true,
      "managerID": "iqzGK08BABCAXcbW2VGwrg==",
      "referenceName": "ActiveList",
      "referenceString": "<Resource URI=\"/All Active Lists/Personal/" + pm.variables.get("login") + "'s Active Lists/" + activeListName + "\" ID=\"\"/>",
      "referenceType": 24,
      "uri": "/All Active Lists/Personal/" + pm.variables.get("login") + "'s Active Lists/" + activeListName + "\""

Upvotes: 2

Views: 4457

Answers (1)

Danny Dainton
Danny Dainton

Reputation: 25921

I think I understand the question but I might be wrong. This seems to work fine for me:

{
  "{{something}}.getEntries": {
    "{{something}}.authToken": {{my_value}},
    "{{something}}.resourceId": {{my_value}}
  }
}

I have these save as environment variables as the values referenced in the POST body - These could be set in a pre-request script easily enough.

Request Body

When the request is sent, it sends through the variable values in the POST body:

Request Body Sent

I might be misunderstanding the question and what you're trying to achieve but i'm happy to update my answer if you provided more details.

Upvotes: 3

Related Questions