I am trying to do a simple template condition but it is resolving differently between the dev tools and script. The dev tools is correct as the outcome of the test should be false.
Dev tools:
{{ states.sensor.media_card_player_id.state }}
{% set queue_info = {
"media_player.ma_kitchen_speaker": {
"queue_id": "4286a323-cabd-9c52-fc5e-d36164e2a2c4",
"current_item": null
}
}
%}
{{ queue_info[states.sensor.media_card_player_id.state]['current_item'] is defined }}
But here we can see the script is failing because the template conditions are resolving to true
The value of current_item is set to the variable null which isn’t defined in your template test. null is not a keyword or value in Jinja, so Jinja treats it like a variable. JSONs null equivalent in jinja is None. Which makes the value of current_itemUndefined, which is why it’s returning false.
Your test in the template editor should be:
{{ states.sensor.media_card_player_id.state }}
{% set queue_info = {
"media_player.ma_kitchen_speaker": {
"queue_id": "4286a323-cabd-9c52-fc5e-d36164e2a2c4",
"current_item": None
}
}
%}
{{ queue_info[states.sensor.media_card_player_id.state]['current_item'] is not none }}
And your code in your automation should be
{{ queue_info[states.sensor.media_card_player_id.state]['current_item'] is not none }}
The only way is defined will properly work is if the key is completely omitted from your json (which it’s not).
So given that the action I am using returns current_item: null is @Hellis81 solution of casting to a string and then testing the best option for me? I have tried it and it seems to work? Or is the is not none test the best practice (I will try it now)
No, the best option is to use the template I provided. The value is null so check for it being None. I.e. {{ queue_info[states.sensor.media_card_player_id.state]['current_item'] is not none }}
And please note the case that I’ve been using. null in json is equal to None in jinja. To check for None, you need to use none test. Which results in using is not none.