Ansible: Remove whitespaces in json file

Solution 1:

You can read it from json and convert back into json with separators option.

{{ my_json_content | from_json | to_json(separators=(',',':')) }}

Note: this is not documented, but if you look at the source code you will see that the filter accepts arbitrary keywords args which are later passed to the python json.dumps function. So you can basically pass to to_json any parameter accepted by json.dumps.

playbook.yml

---
- hosts: localhost
  vars:
      my_json_content:
        '
          { "a" :   0,

          "b":   1,

            "c":    2}

        '
  tasks:
    - debug:
        msg: "json = {{ my_json_content }}"
    - debug:
        msg: "minified_json = {{ my_json_content | from_json | to_json(separators=(',',':')) }}"

$ ansible-playbook playbook.yml

TASK [debug] *******************************************************************
ok: [localhost] => {
    "msg": "json =  { \"a\" :   0,\n\"b\":   1,\n\"c\":    2}\n"
}

TASK [debug] *******************************************************************
ok: [localhost] => {
    "msg": "minified_json = {\"a\":0,\"c\":2,\"b\":1}"
}