What do the filters to_json, to_yaml, to_nice_json, to_nice_yaml, from_json and from_yaml do?
The to_* filters turn a variable (list or dictionary) into JSON or YAML text, the to_nice_* versions indented for humans; from_json and from_yaml go the other way and turn a JSON or YAML string into data.
A filter is written after a pipe and transforms the value before it is output: {{ value | filter }}.
{{ output | to_json }}
{{ output | to_yaml }}
{{ output | to_nice_json }}
{{ output | to_nice_yaml }}
With output: {name: web, ports: [80, 443]}:
| Filter | Result |
|---|---|
to_json |
{"name": "web", "ports": [80, 443]} on one line |
to_nice_json |
the same, spread over lines with indentation |
to_yaml |
compact YAML |
to_nice_yaml |
block-style YAML, one key per line |
This is how a template writes a whole JSON or YAML config file from a variable without building the syntax by hand.
The reverse filters need a string. {{ result.stdout | from_json }} turns the JSON text a command printed into a dictionary you can index ((result.stdout | from_json)['status']). Applied to data that is already a dictionary, they make no sense; they parse text.
Go deeper:
Using filters to manipulate data (official docs) — the formatting filters and many others.
ansible.builtin.from_json filter (official docs) — parsing JSON strings into data.