How to generate JSON with escaped quotes

2,246 views
Skip to first unread message

oss.m...@gmail.com

unread,
May 1, 2017, 2:21:09 PM5/1/17
to Ansible Project
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

Matt Martz

unread,
May 1, 2017, 2:31:37 PM5/1/17
to ansible...@googlegroups.com
I'd look at using the to_json filter instead of replace.

body: {"data":"{{ lookup('file', 'files/example.json') | to_json }}"}

--
You received this message because you are subscribed to the Google Groups "Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email to ansible-proje...@googlegroups.com.
To post to this group, send email to ansible...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/ansible-project/ff4f52a6-c100-4ce5-b71d-dd954261bffc%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
--
Matt Martz
@sivel
sivel.net

oss.m...@gmail.com

unread,
May 3, 2017, 9:11:24 AM5/3/17
to Ansible Project
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
Reply all
Reply to author
Forward
0 new messages