I want to create a sensor based on JSON data, retrieved using a RESTful sensor.
I have got a website with apartment data in JSON format. I use a RESTful sensor to search through this data, looking for the apartment with the newest publicationDate attribute. This sensor sets its state to the corresponding id. My pseudocode is basically as follows:
count = length of JSON
for x in rande(0 to count):
if json[x].publicationDate > previous publicationDate:
newestId = json[x].id
previous publicationDate = json[x].publicationDate
elseif
endfor
return newestId
I want to use the output of this sensor (called nieuwste_woningen
) as attribute path for another sensor (calledwoning_details
). I would like to do this, so I can store details of this particular apartment as attributes in this sensor. Since id
is stored as string in my json, gives json_attributes_path: "$.result.[?(@.id=='26539')]"
me the right result i am looking for. However, json_attributes_path: "$.result.[?(@.id==states.sensor.woning_details)]"
is not working. I have been trying a lot of variations of this line, but nothing seems to work.
My full code is as follows:
sensor:
- platform: time_date
display_options:
- 'time'
- 'date'
- platform: rest
name: nieuwste_woning
resource: https://www.woonkeus-stedendriehoek.nl/portal/object/frontend/getallobjects/format/json
value_template: >-
{% set variables = namespace() %}
{% set count = value_json.result | list | length %}
{% set variables.pub_date = strptime(value_json.result[0]["publicationDate"], "%Y-%m-%d %H:%M:%S") %}
{% set variables.num = value_json.result[0]["id"] %}
{% for x in range(count) %}
{% if strptime(value_json.result[x]["publicationDate"], "%Y-%m-%d %H:%M:%S") > variables.pub_date %}
{% set variables.pub_date = strptime(value_json.result[x]["publicationDate"], "%Y-%m-%d %H:%M:%S") %}
{% set variables.num = value_json.result[x]["id"] %}
{% endif %}
{% endfor %}
{{ variables.num }}
- platform: rest
name: woning_details
json_attributes_path: "$.result.[?(@.id=='26539')]"
json_attributes:
- street
- houseNumber
- totalRent
resource: https://www.woonkeus-stedendriehoek.nl/portal/object/frontend/getallobjects/format/json
value_template: "ok"
This is with "$.result.[?(@.id=='26539')]"
hardcoded, but i would like to use the output of nieuwste_woning
instead of '26539'
.
I get my json from Here
How can I go about solving this? If someone has any other improvements, please tell me. My code might not be the prettiest or most efficient.