[SOLVED] How to cope with special characters in JSON MQTT values

Just wanted to put this here for future reference:

I have a smartmeter that enacpsulates its data over MQTT in JSON like so:

{
  "timestamp":"23.10.2023 22:12:36",
  "+A":77.205,
  "-A":0,
  "+R":2.152,
  "-R":185.659,
  "+P":647,
  "-P":0,
  "+Q":7,
  "-Q":204
}

using this in a sensor like this:

    - name: "energy_P"
      unique_id: "energy_P"
      state_topic: "house/smartmeter/state"
      unit_of_measurement: "W"
      value_template: "{{ value_json.+P }}"

just gives an error on the last line, because “value_json.+P” does not parse correctly.
But since “value_json” is a dictionary, we can write

      value_template: "{{ value_json['+P'] }}"

instead and it works fine!
(Note the single quotes, since double quotes are already used on the outside!)

1 Like

Bracket notation is always safer than dot notation.

Welcome!

and welcome to the ‘wonderful’ world of jinja2 and JSON parsing… Two good examples why to combine Home Automation with liberal quantities of :wine_glass: and/or :beer: makes ‘sensor’ sense…