Bootstrap FreeKB - Ansible - Convert dictionary to string using to_json
Ansible - Convert dictionary to string using to_json

Updated:   |  Ansible articles

Let's say you are fetching JSON or a dictionary from something outside of Ansible. For example, perhaps you are using ansible.builtin.shell to run a homegrown script that returns JSON or a dictionary. For example, something like this.

---
- hosts: localhost
  tasks:
  - name: invoke homegrown script.py
    ansible.builtin.shell: /path/to/homegrown/script.py
    register: out
    
  - ansible.builtin.debug:
      var: out.stdout

 

Let's say the above playbook returns the following, which means that the homegrown script returned JSON or a dictionary.

ok: [localhost] => {
    "out": {
        "result": "success",
        "data": "hello world",        
    }
}

 

The type_debug filter can be used to display the type of object that Ansible is registering.

- ansible.builtin.debug:
    var: out.stdout | type_debug

 

Which should return something like this, in this scenario, almost always a str or dict.

ok: [localhost] => {
    "out.stdout | type_debug": "dict"
}

 

Depending on the flavor and version of Ansible that you are using, you may be able to print the values of the keys like this.

- ansible.builtin.debug:
    var: out.stdout.result
    
- ansible.builtin.debug:
    var: out.stdout.data    

 

On the other hand, some flavors or versions of Ansible will require you to use the to_json filter because Ansible is detecting that the out variable is a dict and not a string, thus to_json is needed to convert the out variable from a dict to a string.

Similarly, from_json can be used to convert a dictionary to a string.

- ansible.builtin.debug:
    var: (out.stdout | to_json).result
    
- ansible.builtin.debug:
    var: (out.stdout | to_json).data

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 140ff7 in the box below so that we can be sure you are a human.