How to escape double quote when setting/using variables?

Iโ€™m making two API calls. The first returns JSON with one of the values being HTML as a string.

{ "html_content": "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0..." }

In the Tests section, I am setting a collection variable with this string.

pm.collectionVariables.set("htmlContent", pm.response.json().html_content)

Then, in the second API call, I am trying to POST the HTML string.

{ "html_content": "{{htmlContent}}" }

However, Iโ€™m getting a 400 because Postman is sending the string without the double quotes escaped, so the JSON is malformed.

{ "html_content": "<!DOCTYPE html PUBLIC "- //W3C//DTD XHTML 1.0... }

But if I simply copy the HTML output from the first API call and paste it into the second API call, it works (because the escaped double-quotes are still there).

So, my question is this: how do I instruct Postman to keep the escaping in place when I use the collection variable?

Hey @jagrdude

Welcome to the community!! :star:

This might be what you need:

pm.collectionVariables.set("htmlContent", JSON.stringify(pm.response.json().html_content))

And then use this in the POST body like this:

    "html_content": {{htmlContent}}
1 Like

@danny-dainton - youโ€™re the man! That did the trick. :+1:

I know I tried a variation of that, but I think my misstep was I left the double quotes around the variable reference: "{{htmlContent}}"

Removing that along with the stringifying was the solution.

Thanks for the help and quick response!

1 Like