Ansible from_json & to_json Filters: Parse and Generate JSON Data (Guide)

By Luca Berton · Published 2024-01-01 · Category: troubleshooting

Complete guide to Ansible from_json and to_json filters. Parse JSON strings into data structures and convert variables to JSON format in playbooks.

What Are from_json and to_json Filters?

The from_json and to_json filters convert data between JSON strings and Ansible data structures: • from_json: Parses a JSON string into a dictionary or list • to_json: Converts a variable (dict, list) into a JSON string • to_nice_json: Converts to human-readable formatted JSON

from_json: Parse JSON Strings

Use from_json when you receive JSON as a string (from API calls, command output, file reads):

Parse JSON from Command Output

Parse JSON from File

to_json: Convert to JSON Strings

Use to_json to convert Ansible variables to JSON format:

Write JSON to File

Send JSON in API Requests

to_nice_json: Human-Readable Output

to_nice_json produces formatted, indented JSON:

Output:

Control Indentation

to_nice_yaml: Convert to YAML Format

Convert variables to readable YAML:

Common Patterns

Chain Filters

Handle JSON in Loops

Merge and Convert

Error Handling

Invalid JSON

Default Values

FAQ

What is the difference between from_json and from_yaml?

from_json parses JSON strings only. from_yaml parses YAML strings (which is a superset of JSON). In practice, from_yaml can also parse JSON, but from_json is stricter and preferred when you know the input is JSON.

When do I need from_json vs just accessing the variable?

You need from_json when the data is a string containing JSON, not a parsed data structure. This happens with command output (register), file reads (slurp), and API responses returned as strings. If the variable is already a dict/list, you don't need it.

How do I handle nested JSON with special characters?

Use bracket notation for keys with dots or spaces: {{ (json_str | from_json)['my.key']['with spaces'] }}. For complex nested queries, use the json_query filter with JMESPath syntax.

Related ArticlesAnsible Jinja2 Filters GuideAnsible map FilterAnsible dict2items & items2dictAnsible combine Filter

Category: troubleshooting

Browse all Ansible tutorials · AnsiblePilot Home