How to generate JSON with escaped quotes

Hello,
I need to get JSON as string with quotes escaped by a single backslash. Original JSON is in file and I need to send it as string in another JSON body using URI module. I’m able to get only string with quotes escaped as \\" instead of ".

// file example.json
{“a”:“b”,“c”:“d”}

// I need to get {"a":"b","c":"d"} to embed it in uri module

  • uri
    url: http://…
    body: {“data”:“{{ lookup(‘file’, ‘files/example.json’) | replace(‘"’, ‘\"’) }}”}

It generates: {\"a\":\"b\",\"c\":\"d\"}
It is not just escaping in debug, I save it to file using copy module and it has multiple backslashes.

Many thanks,
Petr

I’d look at using the to_json filter instead of replace.

body: {“data”:“{{ lookup(‘file’, ‘files/example.json’) | to_json }}”}

Thank you so much,
it did the trick… almost. I had to add single quotes enclosing the whole expression. Otherwise it defensively renders multiple escape backslashes.

Petr