Variables inside JSON bodies: strings, numbers, arrays and quotes

A request body like {"userId": "{{userId}}", "amount": {{amount}}} looks simple. It is, once you know one rule: a variable is replaced by its text, exactly where it stands. The JSON around it decides what that text becomes.

Strings, numbers, booleans

Variables always hold text. The quotes in your body decide the type:

JSON
{
  "email": "{{email}}",
  "age": {{age}},
  "active": {{isActive}},
  "managerId": {{managerId}}
}

With [email protected], age=34, isActive=true, managerId=null, the server receives:

JSON
{ "email": "[email protected]", "age": 34, "active": true, "managerId": null }

Quote a number ("{{age}}") and the API gets the string "34". Some APIs accept it, strict ones return 400. That's a useful negative test, and a confusing bug when it's an accident.

Arrays and objects

A script can store an array or object; it's saved as JSON text (see the CLI docs on variables). Put it in the body without quotes:

JavaScript
// Tests on "List products"
const ids = pm.response.json().items.map((item) => item.id);
pm.environment.set('productIds', ids);
JSON
{ "productIds": {{productIds}}, "note": "bulk update" }

becomes {"productIds": ["p_1", "p_2", "p_3"], "note": "bulk update"}.

When a value breaks the JSON

A string variable is pasted as is, between your quotes. These values break the body:

  • a double quote: O"Brien → "name": "O"Brien",
  • a backslash: C:\temp,
  • a line break, as in an address or a multi-line comment.

The server answers 400 with a JSON parse error, and the request looks fine in the editor. Two fixes:

Store the escaped text. In a pre-request script, escape it with JSON.stringify and drop the outer quotes:

JavaScript
const raw = pm.iterationData.get('comment');
pm.variables.set('commentJson', JSON.stringify(raw).slice(1, -1));
JSON
{ "comment": "{{commentJson}}" }

Or build the whole body in the script. Clearer when several fields are tricky; see build request bodies in a pre-request script.

Empty and missing values

  • A variable that doesn't exist isn't silently replaced with nothing: the request stops with an unresolved variable, and the editor marks it. See find missing variables before you send.
  • A variable that exists but is empty gives "email": "" in quotes, and broken JSON ("age": ,) without. If a number can be empty, use null as its value, not an empty string.

Dynamic variables

Built-in dynamic variables follow the same rule. "{{$guid}}" and "{{$randomEmail}}" go in quotes; {{$randomInt}} without, if you want a number. Each one is generated once per request, so using {{$guid}} twice in one body gives two different values. Save it to a variable in a pre-request script if you need the same one twice.