Hello.
My openmqttgateway compiled in pilight mode return json string (with weather stations data). Еach station has its own id, and I need to separate them into different sensors. So so i need to use templates. But I got an unexpected issuе, when debug my template in dev->template:
-1-
{% set val = states('sensor.gatewaypilight') %}
{{ val }}
-2-
{{ val.id }}
-3-
{% set val = {'id': 159, 'temperature': 23.5, 'humidity': 55.0, 'battery': 1} %}
{{ val }}
-4-
{{ val.id }}
The post referenced by @VDRainer probably tells you what you need to know. To answer your exact question, though:
Two things:
Firstly, you need to use the from_json filter to interpret the sensor’s state as JSON rather than a string (docs), so
{{ (val|from_json).id }}
Also, I’d be careful with keys like id that might well be an underlying property of the HA definition of a sensor. To guard against this, use this type of lookup instead:
I was faced with a similar situation recently and I used the replace("'", '"') technique but then pnbruckner suggested that I simply use to_json like this:
{% set val = states('sensor.gatewaypilight') | to_json %}
The Jinja2 interpreter used by the Template Editor is lax about what it considers to be “proper JSON”. It readily accepts single-quotes within a dictionary. However, the JSON parser used for Template Sensors is strict and rejects the use of single quotes. That means a template that handles “single-quoted JSON” in the Template Editor is likely to fail when used in a Template Sensor (if supplied with “single-quoted JSON”).
In the Template Editor, it accepts either single or double-quotes within a JSON dictionary. It’s been my experience that Template Sensors fed single-quoted JSON aren’t so accommodating.
Yes, I understand that when the Template Sensor receives the stringified JSON payload it converts it to a JSON dictionary … and if the stringified JSON uses single-quotes, the conversion process throws an error.
In retrospect my use of the word “lax” was misleading. If you’re defining a JSON dictionary in the Template Editor, it accepts either single or double-quotes. It’s the conversion process, from stringified JSON to JSON, that wants to see double-quotes. So when someone use the Template Editor to experiment with JSON dictionaries (not stringified but a proper dictionary) they may be led to believe that single-quotes are fair-game until they actually try feeding that format (stringified JSON) through the conversion process.
Right, but maybe you were missing the fact that OP was grabbing the value dictionary from a state meaning its a string… Which is why to_json will not work as well as any of the templating attempts in the thread aside from wrapping the attempts in quotes to make it a string.