MQTT value_template and value_json understanding

I’m not understanding this section of the help page.

The example shows, the value_json.on (references the “on” in the msg?) grabs the value “true”? So I thought I would duplicate this in mine, but I get the error below.

My MQTT sensor:

  - platform: mqtt
    unique_id: '123456HomeAssistantShutDown'
    state_topic: "homeassistant/CMD/shutdown"
    value_template: "{{ value_json.cmd }}"

My MQTT payload:

{"type":"HA","cmd":"SHUTDOWN"}

When I send that msg I get this error in the logs:

Logger: homeassistant.helpers.template
Source: helpers/template.py:1791
First occurred: 12:22:40 PM (1 occurrences)
Last logged: 12:22:40 PM

Template variable error: ‘value_json’ is undefined when rendering ‘{{ value_json.cmd }}’

Did you use, e.g., MQTT Explorer to ensure what you think you sent is actually in the specified topic?

I did indeed.

Well, what you show lacks the double quotes needed to make it proper JSON.
As it’s not valid json, value_json is undefined.

Random example:

1 Like

Isn’t that something… here is the entire command,. isn’t this correct? Do I need 2 sets of double quotes?

-h 192.168.1.26 -t homeassistant/CMD/shutdown -m {“type”:“HA”,“cmd”:“SHUTDOWN”}

I checked the json format and it shows valid.

I’m wondering now if this is an artifact of using mosquitto_pub command line interface. Stripping the quotes.? Hmmmm

Holy crap… That was it…

I needed to escape the quotes… Aye Caramba…

{\"type\":\"HA\",\"cmd\":\"SHUTDOWN\"}

Thank you for the clarity from your question / response. That’s what let to the solution.