Parsing json data - trying for hours

Hi,

After trying for hours it gets me a headache. Getting my data from a tcp sensor. The data I receive looks like this

[{"path": "sdb", "model": "WDC WD30EZRX-00S", "temperature": 17.0}, {"path": "sda", "model": "Samsung SSD 840", "temperature": 14.0}]

I can’t even get to access values within the developer tools. However when I set the data manually there, it works as expected

{% set value_json = [{"path": "sdb", "model": "WDC WD30EZRX-00S", "temperature": 17.0}, {"path": "sda", "model": "Samsung SSD 840", "temperature": 14.0}] %}
{{ value_json[0]['path'] }}
{{ value_json[1]['temperature'] }}

But it does not when trying to use the data coming from the sensor. Maybe I just don’t see the issue anymore because of testing for hours and hours now.

{% set value_json2 = states('sensor.mysensor') %}
{{ value_json2[0]['path'] }}

It displays the data in the developer tools however:

{{ states('sensor.mysensor') }}

Error I get is

'str object' has no attribute 'path'

Would really appriciate any help from the pros here.

Because the state value of any entity is always handled as a string. If the value is a number or a list in JSON format (what you have) it’s still handled as a string. That’s why this fails:

{% set value_json2 = states('sensor.mysensor') %}
{{ value_json2[0]['path'] }}

Try this:

{% set value_json2 = states('sensor.mysensor') | from_json %}
{{ value_json2[0]['path'] }}

That should work provided that double-quotes, not single quotes, are used to delimit the keys and values of the two dictionary entries in the list (your example uses double-quotes so it should be fine).

For future reference, if it uses single quotes then you need an extra step:

{% set value_json2 = states('sensor.mysensor') | replace("'", '"') | from_json %}
{{ value_json2[0]['path'] }}

Oh my! Can’t believe that, you made my friday afternoon, thank you so much!

1 Like