Skip to content

Commit

Permalink
Adding custom indentation of YAML and JSON filters (ansible#10008)
Browse files Browse the repository at this point in the history
  • Loading branch information
jtyr authored and bcoca committed Jun 14, 2016
1 parent e1d248d commit 27d0659
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 5 deletions.
5 changes: 5 additions & 0 deletions docsite/rst/playbooks_filters.rst
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,11 @@ For human readable output, you can use::
{{ some_variable | to_nice_json }}
{{ some_variable | to_nice_yaml }}

It's also possible to change the indentation of both::

{{ some_variable | to_nice_json(indent=2) }}
{{ some_variable | to_nice_yaml(indent=8) }}

Alternatively, you may be reading in some already formatted data::

{{ some_variable | from_json }}
Expand Down
11 changes: 6 additions & 5 deletions lib/ansible/plugins/filter/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,16 +75,16 @@ def to_yaml(a, *args, **kw):
transformed = yaml.dump(a, Dumper=AnsibleDumper, allow_unicode=True, **kw)
return to_unicode(transformed)

def to_nice_yaml(a, *args, **kw):
def to_nice_yaml(a, indent=4, *args, **kw):
'''Make verbose, human readable yaml'''
transformed = yaml.dump(a, Dumper=AnsibleDumper, indent=4, allow_unicode=True, default_flow_style=False, **kw)
transformed = yaml.dump(a, Dumper=AnsibleDumper, indent=indent, allow_unicode=True, default_flow_style=False, **kw)
return to_unicode(transformed)

def to_json(a, *args, **kw):
''' Convert the value to JSON '''
return json.dumps(a, cls=AnsibleJSONEncoder, *args, **kw)

def to_nice_json(a, *args, **kw):
def to_nice_json(a, indent=4, *args, **kw):
'''Make verbose, human readable JSON'''
# python-2.6's json encoder is buggy (can't encode hostvars)
if sys.version_info < (2, 7):
Expand All @@ -99,9 +99,10 @@ def to_nice_json(a, *args, **kw):
pass
else:
if major >= 2:
return simplejson.dumps(a, indent=4, sort_keys=True, *args, **kw)
return simplejson.dumps(a, indent=indent, sort_keys=True, *args, **kw)

try:
return json.dumps(a, indent=4, sort_keys=True, cls=AnsibleJSONEncoder, *args, **kw)
return json.dumps(a, indent=indent, sort_keys=True, cls=AnsibleJSONEncoder, *args, **kw)
except:
# Fallback to the to_json filter
return to_json(a, *args, **kw)
Expand Down

0 comments on commit 27d0659

Please sign in to comment.