Break up rest JSON reponse which contains dictionary with 3 similar key:value pairs

Hope it’s the right forum.

Currently I have a rest sensor:
value_template: "{{ value_json }}"
It nicely captures the result of the json response. However, this particular json is setup somewhat annoyingly. So the result looks as follows:
[{'afvalstroom_id': 5, 'ophaaldatum': '2023-03-21'}, {'afvalstroom_id': 2, 'ophaaldatum': '2023-03-28'}, {'afvalstroom_id': 6, 'ophaaldatum': '2023-04-11'}]
When I take the value of value_json[0], it will give me the first entry of the dictionary only.

So I guess I need to do some templating, to parse the three different options to a date. Here’s where i’m struggling.

I tried the following, to no avail.

- platform: template
  sensors:
    restafval:
      friendly_name: "Rest Afval"
      value_template: "{{ state_attr('sensor.afval', '5')['ophaaldatum'] }}"

How do I parse the dictionary based on the key? I want to build three sensors, based on the key-value pairs. So key x represents var1, key y represents var2 and key z represents var3 (of which I only need the date as value actually).

Use the RESTful integration.

rest:
  - authentication: basic
    username: "your_username"
    password: "your_password"
    scan_interval: 60
    resource: http://your_url_goes_here
    sensor:
      - name: 'Afvalstroom 5'
        value_template: >
          {{ value_json | selectattr('afvalstroom_id', 'eq', 5)
            | map(attribute='ophaaldatum')
            | list | first | default('unknown') }}
      - name: 'Afvalstroom 2'
        value_template: >
          {{ value_json | selectattr('afvalstroom_id', 'eq', 2)
            | map(attribute='ophaaldatum')
            | list | first | default('unknown') }}
      - name: 'Afvalstroom 6'
        value_template: >
          {{ value_json | selectattr('afvalstroom_id', 'eq', 6)
            | map(attribute='ophaaldatum')
            | list | first | default('unknown') }}
1 Like