I am having a problem parsing some JSON formatted MQTT messages. The template handler (value_template) refuses to accept the following JSON string:
{“temperature”:“69.0”,“humidity”:“31.1”,“airQualityIndex”:“4”,}
but will parse:
{“temperature”:“69.0”,“humidity”:“31.1”,“airQualityIndex”:“4”}
The only difference is the trailing comma before the closing bracket. Python is forgiving on trailing commas in dictionaries, but the HA JSON parser apparently is not. I don’t have the ability to change the code on the device sending the MQTT message. I am trying to migrate over from openhab and it parsed the messages just fine.
Or if someone call tell me how to edit out the extra “,” before passing it to the JSON parser. value_json seems to always use the original string.
JSON format is strictly defined as no trailing commas, so the parser is only doing what it should be doing and rejecting malformed JSON.
Did a quick search and found this: python - Can json.loads ignore trailing commas? - Stack Overflow. One response suggests importing ast, and using ast.literal_eval() which seems to do the trick. You could create a simple macro so you can call it from Jinja templates.
I should(n’t have to) mention that this likely comes with significant security risks, since you’re evaluating stuff from an external source - so, be careful I suppose
Thanks for looking. I figured that was the sort of answer I would get. In anycase I figured out a workaround:
value_template: >
{% set x = value %}
{% if x[-2] == ‘,’ %} {% set x = x[0:-2] + ‘}’ %}
{% endif %}
{% set y = x|from_json %}
{{ y.temperature | float }}
FWIW, the following template uses regex to extract the first number from the supplied string.
{{ value | regex_findall_index('(\d+)', 0) }}
The assumption is that the first number in the string always corresponds to temperature. The regex pattern is designed to extract 1 or more digits. It would need to be enhanced in order to return negative numbers.