How to extract values from a supposedly JSON string?

How to extract values from a supposedly JSON string from an attribute?
ADB integration returns this:

adb_response: {'screen_on': True, 'awake': True, 'audio_state': 'idle', 'wake_lock_size': 5, 'current_app': 'com.google.android.youtube.tv', 'media_session_state': 3, 'audio_output_device': 'speaker', 'is_volume_muted': False, 'volume': 2, 'running_apps': None, 'hdmi_input': None}

In templates error 'str object' has no attribute 'screen_on':

{% set temp = state_attr('media_player.android_tv_10_2_90_12', 'adb_response') %}
{% set temp2 = temp|to_json %}
object|to_json: {{ temp2 }}
{{ temp2.screen_on }}

Needs a bit of cajoling to get it into valid JSON:

{% set temp = "{'screen_on': True, 'awake': True, 'audio_state': 'idle', 'wake_lock_size': 5, 'current_app': 'com.google.android.youtube.tv', 'media_session_state': 3, 'audio_output_device': 'speaker', 'is_volume_muted': False, 'volume': 2, 'running_apps': None, 'hdmi_input': None}" %}
{% set temp2 = temp.replace("'",'"').replace(": True",": true").replace(": False",": false").replace(": None",": null") %}
{% set temp3 = temp2|from_json %}

{{ temp3['screen_on'] }}

…and note that it’s |from_json to turn a string into an object.

So in one line:

{{ (state_attr('media_player.android_tv_10_2_90_12', 'adb_response').replace("'",'"').replace(": True",": true").replace(": False",": false").replace(": None",": null")|from_json)['screen_on'] }}
1 Like

It works! Thanks buddy!
I also saw that this is a little less JSON than he should be. I also tried to replace characters. But something didn’t work out.
But your line works exactly as it should

1 Like