REST Sensor with JSON parsing

Hi there!

I would like to add a sensor to my HA by using API shared by my local transportation company:
[http://ckan2.multimediagdansk.pl/delays?stopId=1274]

Example JSON:
{"lastUpdate":"2020-02-04 21:22:51","delay":[{"id":"T32R167","delayInSeconds":21,"estimatedTime":"21:33","headsign":"Wały Piastowskie","routeId":167,"tripId":32,"status":"REALTIME","theoreticalTime":"21:33","timestamp":"21:22:50","trip":1097125,"vehicleCode":2674,"vehicleId":145727},{"id":"T22R168","delayInSeconds":-175,"estimatedTime":"21:50","headsign":"Wrzeszcz PKP","routeId":168,"tripId":22,"status":"REALTIME","theoreticalTime":"21:53","timestamp":"21:22:50","trip":1112941,"vehicleCode":2043,"vehicleId":41}]}

My current HA configuration:

  - platform: rest
    resource: http://ckan2.multimediagdansk.pl/delays?stopId=1274
    name: travel
    value_template: '{{value_json["delay"][0]}}'

I would like to get “estimatedTime” and “routeID” for all the items.

Thanks in advance for any tips.

This:

    value_template: >
      {% set ns = namespace(items = '') %}
      {% for item in value_json.delay %}
        {% set ns.items = ns.items ~ 'Route: {} Time: {}, '.format(item.routeId, item.estimatedTime) %}
      {% endfor %}
      {{ ns.items }}

produces this:

Route: 167 Time: 21:33, Route: 168 Time: 21:50,

Many thanks @123, this is exactly what I need :slight_smile:

1 Like

Keep in mind that an entity’s state is limited to storing a maximum of 255 characters. That’s enough space to store the information for about ten routes. If you need to store more, you can abbreviate Route: and Time: to just R: and T: to provide extra space for more routes.

@wochen

For the benefit of other members, who may have a similar question, please mark my reply above (the one containing the suggested value_template) with the Solution tag.

Only you, the author of this topic, can do that. It will place a checkmark next to the topic’s title and a link under your first post leading to the Solution. All of this announces to others that this topic has an accepted Solution.

@123
Thank you for your help and suggestion, it’s all done.

1 Like