ansible.builtin.to_json filter – Convert variable to JSON string
Note
This filter plugin is part of ansible-core
and included in all Ansible
installations. In most cases, you can use the short
plugin name
to_json
.
However, we recommend you use the Fully Qualified Collection Name (FQCN) ansible.builtin.to_json
for easy linking to the
plugin documentation and to avoid conflicting with other collections that may have
the same filter plugin name.
Synopsis
Converts an Ansible variable into a JSON string representation.
This filter functions as a wrapper to the Python
json.dumps
function.Ansible internally auto-converts JSON strings into variable structures so this plugin is used to force it into a JSON string.
Input
This describes the input of the filter, the value before | ansible.builtin.to_json
.
Parameter |
Comments |
---|---|
A variable or expression that returns a data structure. |
Keyword parameters
This describes keyword parameters of the filter. These are the values key1=value1
, key2=value2
and so on in the following
example: input | ansible.builtin.to_json(key1=value1, key2=value2, ...)
Parameter |
Comments |
---|---|
When Choices:
|
|
Controls the usage of the internal circular reference detection, if off can result in overflow errors. Choices:
|
|
Escapes all non ASCII characters. Choices:
|
|
Number of spaces to indent Python structures, mainly used for display to humans. Default: |
|
Toggle to represent unsafe values directly in JSON or create a unsafe object in JSON. Choices:
|
|
The Default: |
|
If Choices:
|
|
Affects sorting of dictionary keys. Choices:
|
|
Toggle to either unvault a vault or create the JSON version of a vaulted object. Choices:
|
Notes
Note
Both
vault_to_text
andpreprocess_unsafe
defaulted toFalse
between Ansible 2.9 and 2.12.These parameters to
json.dumps
will be ignored, as they are overridden internally: cls, default
Examples
# dump variable in a template to create a JSON document
{{ docker_config | to_json }}
# same as above but 'prettier' (equivalent to to_nice_json filter)
{{ docker_config | to_json(indent=4, sort_keys=True) }}
Return Value
Key |
Description |
---|---|
The JSON serialized string representing the variable structure inputted. Returned: success |