Json data parse from rest

Hi,
I have the following json data:

{"software_version": "NRZ-2020-133", "age":"9", "sensordatavalues":[{"value_type":"SDS_P1","value":"41.33"},{"value_type":"SDS_P2","value":"29.70"},{"value_type":"BME280_temperature","value":"0.65"},{"value_type":"BME280_pressure","value":"92408.47"},{"value_type":"BME280_humidity","value":"77.31"},{"value_type":"samples","value":"4993373"},{"value_type":"min_micro","value":"28"},{"value_type":"max_micro","value":"20231"},{"value_type":"interval","value":"145000"},{"value_type":"signal","value":"-80"}]}

I’m getting the data successfully with a http request but I’m not able to parse the values where value_type is SDS_P1 and SDS_P2.

This is the configuration I have currently:

sensor:
  - platform: rest
    name: home_air_quality
    json_attributes:
     - sensordatavalues
    resource: http://192.168.8.20/data.json
    value_template: "OK"

  - platform: template
    sensors:
     pm10:
      friendly_name: "PM 10"
      value_template: '{{ states.sensor.home_air_quality.attributes["sensordatavalues"]["SDS_P1"] }}'
     pm25:
      friendly_name: "PM 2.5"
      value_template: '{{ states.sensor.home_air_quality.attributes["sensordatavalues"]["SDS_P2"] }}'

Thanks

An easy way to determine the correct JSON path is to use JSONPathfinder.

Here’s your data in JSONPathfinder:


It indicates the correct path to the value of SDS_P1 is:

x.sensordatavalues[0].value

Translated into Home Assistant:

      value_template: '{{ states.sensor.home_air_quality.attributes.sensordatavalues[0].value }}'

This will work provided that the data always reports SDS_P1 as the zeroth item in the sensordatavalues list. If that cannot be guaranteed then the template must be enhanced to search through all items in the list to find the one containing SDS_P1.

1 Like

Thanks Taras,
It’s working like this. However as the order can be changed do you know how can I search through the items in order to find the correct value?

Like this:

      value_template: '{{ (states.sensor.home_air_quality.attributes.sensordatavalues | selectattr('value_type', 'eq', 'SDS_P1') | list)[0].value }}'

I used the Template Editor to compose and test the template:

1 Like

Which of the two suggestions that I have provided has proven to work for you?

Currently I’m using the first one and it’s working great.

1 Like

OK, glad to hear to hear it resolves the problem.

Please consider marking my first post with the Solution tag. It will automatically place a check-mark next to the topic’s title. It signals to other users that this topic has an accepted solution and helps people find answers to similar questions.