Simple JSON Question (I think)

Hi All,
I have a problem finding the correct syntax for a value_template instruction to get a value from a MQTT message.
I think it may be very simple for experienced JSON user, but I have tried numerous ways to get the right value but did not succeed yet.

OK so the MQTT message is:

Topic:
'DSMR/energy_delivered_tariff1'
Value:
'{"energy_delivered_tariff1": [{"value": 18887.414, "unit": "kWh"}]}'

And my value_json is:

- platform: mqtt
  state_topic: "DSMR/energy_delivered_tariff1"
  name: 'Energy Delevered Tariff1'
  unit_of_measurement: 'kWh'
  value_template: '{{ value_json["energy_delivered_tariff1"]["value"] }}'

Result in my states overview is empty.
Any ideas
Thx,
PPee

value_template: '{{ value_json["energy_delivered_tariff1"][0]["value"] }}'

OK Taras that did it. Thanks!!
So why oh why the [0]

1 Like

Because this:

[{"value": 18887.414, "unit": "kWh"}]

is a list containing one item. The index value of the first item in a list is zero.

Paste this into the Template Editor and experiment with it:

{% set x = ['cat', 'bat', 'hat'] %}
{{ x[0] }}

{% set x = [{'animal':'horse'}, {'animal':'cow'}] %}
{{ x[0] }}
{{ x[1] }}
{{ x[0]['animal'] }}


Please consider marking my post (above) with the Solution tag. This will automatically place a check-mark next to the topic’s title which signals to other users that this topic has an accepted solution. It serves to help users who may have a similar question and are looking for answers.

1 Like