REST Sensor Issues

Despite digging ad nauseum in both the official docs and googling, I’m at a loss. Here’s what I’m working with, and I’ll explain my issues at the bottom:

configuration.yaml:

sensor:
- platform: rest
  name: "SEPTA_test"
  resource: https://www3.septa.org/api/NextToArrive/index.php?req1=Wilmington&req2=Suburban%20Station&req3=2
  value_template: "{{ value_json[0].orig_departure_time }} {{ value_json[1].orig_departure_time }}"
  json_attributes:
    - "orig_delay"

Current API return:

[
  {
    "orig_train": "9212",
    "orig_line": "Wilmington/Newark",
    "orig_departure_time": "10:11AM",
    "orig_arrival_time": "11:08AM",
    "orig_delay": "6 mins",
    "isdirect": "true"
  },
  {
    "orig_train": "2514",
    "orig_line": "Wilmington/Newark",
    "orig_departure_time": "12:12PM",
    "orig_arrival_time": "1:09PM",
    "orig_delay": "On time",
    "isdirect": "true"
  }
]

Home Assistant sensor:
image

As can be seen, I’m using value_json[0] and value_json[1] to extract each orig_departure_time instance.

My question, however, is how can I extract and identify each instance of orig_delay and nest it under json_attributes? Doing something like this didn’t work:

  json_attributes:
    - "orig_delay[0]"
    - "orig_delay[1]"

You have to use json_attributes_path to select the first item in the list.

Use the RESTful integration instead:

Then, for a single call:

rest:
  - resource: https://www3.septa.org/api/NextToArrive/index.php?req1=Wilmington&req2=Suburban%20Station&req3=2
    sensor:
      - name: "Septa 1"
        value_template: "{{ value_json[0].orig_departure_time }}"
        json_attributes_path: "$.0"
        json_attributes:
          - "orig_train"
          - "orig_line"
          - "orig_departure_time"
          - "orig_arrival_time"
          - "orig_delay"
          - "isdirect"
        availability: "{{ value_json|length > 0 }}"

      - name: "Septa 2"
        value_template: "{{ value_json[1].orig_departure_time }}"
        json_attributes_path: "$.1"
        json_attributes:
          - "orig_train"
          - "orig_line"
          - "orig_departure_time"
          - "orig_arrival_time"
          - "orig_delay"
          - "isdirect"
        availability: "{{ value_json|length > 1 }}"

gets you this:

Add as many more as you need: any “excess” sensors will report unavailable while the list isn’t long enough.

You’ll need to create a template sensor (in YAML, as the UI can’t do attributes yet) with:

attributes:
  septa1_delay: "{{ state_attr('sensor.septa_1', 'orig_delay') }}"
  septa2_delay: "{{ state_attr('sensor.septa_2', 'orig_delay') }}"
# and so on as required

although it might be easier to create many separate sensors with the delay as the state. Depends what you’re trying to do with them.

1 Like