Sum values from json list in a sensor Rest

Hello everyone,

I have this list of data in json that an API returns to me:

{"status":"success","matches":3,"figures":[
  {
    "number": "5677",
    "name": "One",
    "ownedTotal": 5
  },
  {
    "number": "2357",
    "name": "Two",
    "ownedTotal": 1
  },
  {
    "number": "9832",
    "name": "Three",
    "ownedTotal": 8
  }
]}

I would like to sum the “ownedTotal” values in a sensor, I have this REST and sensor:

  - platform: rest
    name: "Collection"
    resource: 'https://web.com/api/v3.asmx/getDATA?apiKey=MYAPI&userHash=MYHASH&params=MYPARAM'
    method: 'GET'
    value_template: '{{ value_json.matches | int }}'
    json_attributes:
      - figures
  - platform: template
    sensors:
      all_sum:
        friendly_name: "All"
        value_template: '{{ SUM NEED  | int }}'

I have tried several ways to do this sum but I have not been able to get it to work correctly,
Thanks for your help

Legacy restful senor platform:

  - platform: rest
    name: "Collection"
    resource: 'https://web.com/api/v3.asmx/getDATA?apiKey=MYAPI&userHash=MYHASH&params=MYPARAM'
    value_template: "{{ value_json.figures[0].ownedTotal + value_json.figures[1].ownedTotal + value_json.figures[2].ownedTotal }}"

Or using the new restful sensor integration:

rest:
  - resource: "https://web.com/api/v3.asmx/getDATA?apiKey=MYAPI&userHash=MYHASH&params=MYPARAM"
    sensor:
      - name: "Collection"
        value_template: "{{ value_json.figures[0].ownedTotal + value_json.figures[1].ownedTotal + value_json.figures[2].ownedTotal }}"

Thanks for your reply Tom,

Would there be a way to do it with a “for” loop, for example for all the values of “ownedTotal”, the list returned by the API really has more than 1000 results (I only put an example with 3 values) and can increase and decrease.

The number of obtainable values is “matches”, but i need the sum of “ownedTotal” for each value,

Best regards.

Reading the documentation of Jinja2 I have found the solution that seems to work for me at the moment:

value_template: "{{ value_json.figures | sum(attribute='ownedTotal') }}"

Maybe it will solve the problem for someone else, thanks.

3 Likes