String variable of json to json in jinja2

Not sure if I’ve termed it correctly, but how do I convert a string variable with json as the value to a actual iterable json object?

e.g. a straight json object works:

{% set json_object = {"room":"bedroom","lights":[{"light_name":"lamp1"},{"light_name":"lamp2"}]}  %}

{% for light in json_object.lights %}
{{ light.light_name }}
{% endfor %}

but a varialbe doesn’t, I’ve tried various things like creatong another variable with the | tojson filter.

(notice the single quote before the value is declared)

{% set json_string = '{"room":"bedroom","lights":[{"light_name":"lamp1"},{"light_name":"lamp2"}]}'  %}

{% for light in json_string.lights %}
{{ light.light_name }}
{% endfor %}

Any assistance is appreciated, for what I’m attempting I can’t get away from using a string variable.

Admittedly slightly confusingly, the correct filter is from_json, as you are creating an object from a JSON string.


A day of struggling and it was that simple. Thank you.

1 Like

You are a bloody legend! This helped me immensely. I got some garbage json I had to manipulate as a string and could not get it back to json!

1 Like