Rest sensor template for passing JSON with objects and arrays (transport times)

Hey there,

I’m still quite new to Home Assisant and have been trying to add a custom transport feed from a PHP script that I put together the returns the next few train departures for two separate lines.

I’m having issues figuring out how to work with the JSON object and array, and breaking it up into separate sensors so I can display it all nicely on lovelace.

A sample JSON response is below:

{
  "lastUpdated": "2021-07-28 15:30:50",
  "Northbound": [
    {
      "plannedDeparture": "15:37",
      "estimatedDeparture": "15:37",
      "timeToEstDepartureMins": 6,
      "delayMins": 0,
      "isDelayed": false,
      "number": "B463"
    },
    {
      "plannedDeparture": "15:55",
      "estimatedDeparture": "15:57",
      "timeToEstDepartureMins": 26,
      "delayMins": 2,
      "isDelayed": false,
      "number": "B121"
    }
  ],
  "Southbound": [
    {
      "plannedDeparture": "15:37",
      "estimatedDeparture": "15:37",
      "timeToEstDepartureMins": 6,
      "delayMins": 0,
      "isDelayed": false,
      "number": "A123"
    },
    {
      "plannedDeparture": "15:55",
      "estimatedDeparture": "15:55",
      "timeToEstDepartureMins": 24,
      "delayMins": 0,
      "isDelayed": false,
      "number": "A317"
    }
  ]
}

I’ve tried following the help documentation, specifically the example on bedroom sensors, but I can’t seem to figure out how to get this to work.

- platform: rest
    name: train_times
    resource: http://192.168.1.32/traintimes/
    json_attributes:
      - Northbound
    value_template: "OK"
  - platform: template
    sensors:
      Northbound1_planneddeparture:
        value_template: "{{ state_attr('sensor.train_times', 'Northbound')['plannedDeparture'] }}"
      Northbound1_estimateddeparture:
        value_template: "{{ state_attr('sensor.train_times', 'Northbound')['estimatedDeparture'] }}"
      Northbound1_timetoestdeparture:
        value_template: "{{ state_attr('sensor.train_times', 'Northbound')['timeToEstDeparture'] }}"
        unit_of_measurement: "Mins"
      Northbound1_number:
        value_template: "{{ state_attr('sensor.train_times', 'Northbound')['number'] }}"
...

It seems to be pulling in some information, but I don’t think I’ve structured this correctly.

I’m not sure if I need to define everything as an individual sensor i.e. Northbound1 (plannedeparture), Northbound2 (plannedeparture) etc, or if this should be done in a different way using templating.

The outcome I’m looking for is to display the next departure few departure times and indicate any delays.

board

Any ideas?

Northbound is a list, so you need this for the first entry:

value_template: "{{ state_attr('sensor.train_times', 'Northbound')[0]['plannedDeparture'] }}"

Fantastic. Thanks so much @Troon