producing json compliant output from jinja template

5,719 views
Skip to first unread message

Rajul Vora

unread,
Feb 12, 2014, 11:23:25 PM2/12/14
to salt-...@googlegroups.com
Hello Salties:

how do I produce double-quoted string list out of jinja that will be JSON compatible?

foo-template:
{
  "foo": {{ pillar['foo'] }}
}

salt/pillar/foo.sls:
foo:
  - 10.1.1.1
  - 10.2.2.2


This when rendered produces single-quoted strings which is not JSON:
{
  "foo": ['10.1.1.1', '10.2.2.2']
}

How can we produce double-quoted strings?

Thanks,

Rajul

David Anderson

unread,
Feb 13, 2014, 12:43:01 AM2/13/14
to salt-...@googlegroups.com
Hi Rajul,

If you're using jinja and if you know that your pillar variables will
never contain single quotes, you could do:

{
"foo": {{ pillar['foo']|replace("'", '"') }}
}

or

{
"foo": ["{{ pillar['foo']|join('", "') }}"]
}

however if you need to escape possible double quotes you can use:

{
"foo": [
{%- for foo in pillar['foo'] -%}
"{{ foo|replace('"', '\\"') }}"
{%- if not loop.last -%}
,
{%- endif -%}
{%- endfor -%}
]
}


--
Dave
> --
> You received this message because you are subscribed to the Google
> Groups "Salt-users" group.
> To unsubscribe from this group and stop receiving emails from it, send
> an email to salt-users+...@googlegroups.com.
> For more options, visit https://groups.google.com/groups/opt_out.

David Anderson

unread,
Feb 13, 2014, 12:46:11 AM2/13/14
to salt-...@googlegroups.com
Sorry, I meant to say "if you know that your pillar variables will never
contain double quotes"
--
Dave

CDSRV TechSupport

unread,
Feb 13, 2014, 12:57:53 AM2/13/14
to salt-...@googlegroups.com
this might be a longshot, but salt has a mongodb "returner" module, which seems like it would produce valid json at some point.

Seth House

unread,
Feb 13, 2014, 9:12:10 AM2/13/14
to salt-...@googlegroups.com

On Feb 12, 2014 10:23 PM, "Rajul Vora" <raju...@gmail.com> wrote:
> how do I produce double-quoted string list out of jinja that will be JSON compatible?
>
> foo-template:
> {
>   "foo": {{ pillar['foo'] }}
> }

Salt has a custom Jinja filter that will convert variables to a JSON string:

{
  "foo": {{ pillar['foo'] | json() }}
}

http://docs.saltstack.com/ref/renderers/all/salt.renderers.jinja.html#variable-and-block-serializers

Rajul Vora

unread,
Feb 13, 2014, 1:38:37 PM2/13/14
to salt-...@googlegroups.com, se...@eseth.com
Thanks everyone. I think this solution seems promising and elegant.

Rajul
Reply all
Reply to author
Forward
0 new messages