Getting a JSON parse error when running a collection if there is a variable in the request body

Here is the body of my request. You will note the {{numProducts}} variable.
{
“query”: {
“bool”: {
“filter”: [
{
“term”: {
“language”: “EN”
}
},
{
“term”: {
“region”: “USA”
}
},
{
“term”: {
“season”: “FA2019”
}
}
]
}
},
“size”:{{numProducts}},
“_source”: [
“language”,
“genderAge”,
“division”,
“productCode”,
“region”
]
}
I also have a pre-req script which has this line : var sources = JSON.parse(pm.request.body.raw)._source.toString();

When I run the request manually, I do not have an issue, but when I run it as part of a collection, I get this error: JSONError: Unexpected token ‘n’ at 23:14 “size”:{{numProducts}}, ^

I think it’s going to be the case that variables in the {{variable}} notation are interpolated at runtime i.e. when the request is executed. As you’re working within the pre-request script, you’ll need to sort it out yourself if that’s what you want to do.

var requestBody = JSON.parse(pm.request.body).raw.replace('{{numProducts}}', pm.variables.get('numProducts'));

Will give you the body in string format, JSON.parse the entire thing if you want it as an object.