MQTT payload_template JSON - Double vs single quotes issue

I am trying to use templating to publish to a MQTT device but am having issues as quotes within the JSON payload are coming out as single instead of double.

This is my payload template I want to publish:
{% set json = {“line”:1,“position”:0,“text”:states.sensor.temperature_outside.state} %}
{{ json }}
which resolves to:
{‘line’: 1, ‘position’: 0, ‘text’: ‘14.2’}

The sensor I’m using does not accept that JSON. However it will accept this:
{“line”: 1, “position”: 0, “text”: “14.2”}

From what I read - proper JSON should be double quotes not single so the sensor is right to ignore the single quote version.

Is it possible to ensure JSON output is produced with double quotes?

If you go to the templating page in HA you can easily replicate the formatting problem:

{% set my_test_json = {
“temperature”: 25,
“unit”: “°C”
} %}
{{ my_test_json }}

Becomes:
{‘temperature’: 25, ‘unit’: ‘°C’}

How can the JSON be formed properly? Is it possible?

{% set my_test_json = {“temperature”: 25,“unit”: “°C”} %}

should be

{% set my_test_json = '“temperature”: 25,“unit”: “°C”' %}

I googled your question and found the answer.

{% set my_test_json = {'temperature':'25', "unit": "C"} %}
{{ my_test_json | tojson}}
1 Like

Ah great thanks - that makes sense, hadn’t thought about hunting around Jinga doc. All new stuff to me but getting into it now!

1 Like