Quantcast
Channel: Configuration - Home Assistant Community
Viewing all articles
Browse latest Browse all 95919

Extracting multiple attributes from JSON?

$
0
0

@Hurde wrote:

I’m using the RESTful integration to acquire data for my bus stop, especially the next three departures for a specific bus line. I’m trying to fetch these values from the JSON response and use them in a sensor. My sensor configuration is below:

  - platform: rest
    method: POST
    name: HSL_LPV_550
    resource: https://api.digitransit.fi/routing/v1/routers/hsl/index/graphql
    payload: '{  stop(id: "HSL:1463113")   {    stopTimesForPattern(id: "HSL:2550:0:01", numberOfDepartures: 3)     {    	realtimeArrival      }  }}'
    headers:
      Content-Type: application/graphql

The POST request gives a response of:

{
  "data": {
    "stop": {
      "stopTimesForPattern": [
        {
          "realtimeArrival": 71746
        },
        {
          "realtimeArrival": 72527
        },
        {
          "realtimeArrival": 72892
        }
      ]
    }
  }
}

The above response contains the desired next three departures, the format is seconds from midnight.

However, here comes the tricky part. I would like to use the values to determine the sensor value and a sensor attribute according to the following formula (I’m comparing the realtimeArrival to the current time):

IF:
the difference on first timestamp and current time is under 4 minutes, set the second timestamp difference as sensor value and third timestamp difference as sensor attribute called next.
ELSE:
set the first timestamp difference as sensor value and second timestamp difference as sensor attribute called next.

I could extract the time difference of first arrival and current time in minutes using the following:

{% set current_time = ((now().hour*60+now().minute)*60+now().second) %}
{% set arrival_time = (value_json.data.stop.stopTimesForPattern[0].realtimeArrival) %}
{% set ETA = ((arrival_time-current_time)/60)  | int %}

My issue could be broken to the following parts:

  1. I don’t know how to extract all three values of the JSON reply and use them in value_template, as they have same names
  2. I don’t know how I can use IF-ELSE statement as described above, this seems trivial as long as I have the three values available somewhere.

Posts: 5

Participants: 3

Read full topic


Viewing all articles
Browse latest Browse all 95919

Trending Articles