Bootstrap FreeKB - Ansible - Convert string to dictionary using from_json
Ansible - Convert string to dictionary using from_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": "str"
}

 

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 from_json filter because Ansible is detecting that the out variable is a string and not a dictionary, thus from_json is needed to convert the out variable from a string to a dictionary.

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

- ansible.builtin.debug:
    var: (out.stdout | from_json).result
    
- ansible.builtin.debug:
    var: (out.stdout | from_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 fbfe80 in the box below so that we can be sure you are a human.