In an Ansible task I'd like to test if string is json prior to use it with from_json.
fatal: [localhost]: FAILED! =>
msg: |-
the field 'args' has an invalid value ({u'tojson': u'{{ notjson | from_json}}'}), and could not be converted to an dict.The error was: No JSON object could be decoded
Thanks in advance for your help.
Invalid JSON will fail. For example
- set_fact:
json_parsed: "{{ json_str|from_json }}"
vars:
json_str: 'invalid JSON'
TASK [set_fact] ****
fatal: [localhost]: FAILED! =>
msg: |-
the field 'args' has an invalid value ({'json_parsed': '{{ json_str|from_json }}'}), and could not be converted to an dict.The error was: Expecting value: line 1 column 1 (char 0)
The error appears to be in '/export/scratch/tmp/test-145.yml': line 21, column 7, but may
be elsewhere in the file depending on the exact syntax problem.
The offending line appears to be:
- set_fact:
^ here
It's possible to handle the error. For example
- set_fact:
json_parsed: "{{ json_str|from_json }}"
vars:
json_str: 'invalid JSON'
ignore_errors: true
register: result
- debug:
msg: "{{ result.msg }}"
when: result.failed
TASK [debug] ****
ok: [localhost] =>
msg: |-
the field 'args' has an invalid value ({'json_parsed': '{{ json_str|from_json }}'}), and could not be converted to an dict.The error was: Expecting value: line 1 column 1 (char 0)
The error appears to be in '/export/scratch/tmp/test-145.yml': line 11, column 7, but may
be elsewhere in the file depending on the exact syntax problem.
The offending line appears to be:
- set_fact:
^ here
Ansible filter from_json is wrapper to Python json.loads
See Error handling in playbooks
See meta on how to end a play or host gracefully.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With