hi
im trying to find a way in template code to check if a string is valid json
checked chagpt but it gave me false answers and non supported syntax
if I do this code
{% set json_string = 'invalid' %}
{% set json_data = json_string | from_json is not none %}
in HA dev templates tab, i get a json decode error and the template rendering is stopped (i.e. if its inside automation or lovelace card)
what is value_json? a function ? how does it get the json string iput to parse ?
i want to check if a string variable json_string has a valid json content
its not an integration
its something i get from some external system as string
is there a way to validate it in template code?
i asked GPT and it says i need to write python script to do this, impossible via template
i get it via some API from my mobile phone
but lets for sake of question assume its just some input text sensor that the user types the value
and i want to validate the value in automation tobe valid json string
is it supported?
This is a general question if HA template can validate a string to be JSON and give either True or False result. This can be done in python / Java code with ease, I want to know if possible via templates
lets say i have this code in dev tools templates
{% set my_string = 'garbage string' %}
{% set valid_json_obj = ( my_string | from_json ) %}
{{ valid_json_obj is not none }}
this gives json decode error and if run via automation, it will stops rendering the automation
in dev tab you get this error
JSONDecodeError: unexpected character: line 1 column 1 (char 0)
but i want instead for it to end with False for above case and I can decide in my templates code what to do after
Itâs not supported by python, you do a try except in python. There is no function in orjson or json that ignores exceptions. And jinja does not support try except.
Ideally from_json would have a default argument so that when it encounters a string it cannot parse it reports the supplied default value as opposed to throwing an error.
For example, the output of this would be none.
{{ 'gobbledygook' | from_json(none) }}
The alternative is it simply defaults to none (or unknown) if it fails to parse the input string.
If it interests you, I suggest you create a Feature Request for it.