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¶ms=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
tom_l
April 13, 2022, 9:31am
2
Legacy restful senor platform:
- platform: rest
name: "Collection"
resource: 'https://web.com/api/v3.asmx/getDATA?apiKey=MYAPI&userHash=MYHASH¶ms=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¶ms=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.
AtomikWiWa
(Atomik WiWa)
April 14, 2022, 10:29am
4
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