Skip to content

to_json

Collection Note

This module is part of the ansible.builtin collection. To install the collection, use:

ansible-galaxy collection install ansible.builtin
Added in version historical.

Synopsis

  • Converts an Ansible variable into a JSON string representation.
  • This filter functions as a wrapper to the Python C(json.dumps) function.
  • Ansible internally auto-converts JSON strings into variable structures so this plugin is used to force it into a JSON string.

Parameters

Parameter Defaults / Choices Comments
_input
raw
required
A variable or expression that returns a data structure.
allow_nan
bool
Default: True
When V(False), strict adherence to float value limits of the JSON specifications, so C(nan), C(inf) and C(-inf) values will produce errors. When V(True), JavaScript equivalents will be used (C(NaN), C(Infinity), C(-Infinity)).
check_circular
bool
Default: True
Controls the usage of the internal circular reference detection, if off can result in overflow errors.
ensure_ascii
bool
Default: True
Escapes all non ASCII characters.
indent
integer
Number of spaces to indent Python structures, mainly used for display to humans.
preprocess_unsafe
bool
Default: True
Toggle to represent unsafe values directly in JSON or create a unsafe object in JSON.
Version Added: 2.9
separators
tuple
Default: (', ', ': ')
The C(item) and C(key) separator to be used in the serialized output, default may change depending on O(indent) and Python version.
skipkeys
bool
If V(True), keys that are not basic Python types will be skipped.
sort_keys
bool
Affects sorting of dictionary keys.
vault_to_text
bool
Default: True
Toggle to either unvault a vault or create the JSON version of a vaulted object.
Version Added: 2.9

Notes

Note

  • Both O(vault_to_text) and O(preprocess_unsafe) defaulted to V(False) between Ansible 2.9 and 2.12.
  • These parameters to C(json.dumps) will be ignored, as they are overridden internally: I(cls), I(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 Values

Key Data Type Description Returned
_value string The JSON serialized string representing the variable structure inputted.

Authors

  • Core Team