Struggling with parsing JSON via Restful

Hey,

Have been spending now 2 nights behind this issue, tried many approaches yet I still cannot figure out what I need to do. Hope that one of you could point me into the right direction please.

I am getting the following JSON back after an API request:

{
    "preferredNextApiRequestAt": {
        "secondOfHour": XXXX,
        "epochTimeUtc": XXXXXXXXXXX
    },
    "status": 0,
    "iLastPredictionGenerationEpochTime": XXXXXXXXXX,
    "weather_source_text": "Kurzfristig (3 Tage): Powered by <a href=\"https://www.weatherapi.com/\" title=\"Free Weather API\">WeatherAPI.com</a> und Langfristig (10 Tage): Powered by <a href=\"https://www.visualcrossing.com/weather-data\" target=\"_blank\">Visual Crossing Weather</a>",
    "datalinename": "Germany > L",
    "data": {
        "20230908": 35.574,
        "20230909": 35.474
    }
}

I need to take the two numbers (35.574 and 35.474) into two sensors. I cannot just call the number descriptors as that string (here: 20230908 and 20230909) change every day, so I thought I need to point to the numbers I want via a list The below is my YAML code. This one does not work, neither the many dozen other approaches I took. Likely this is really easy, but I am stuck…

Any help/hint/tip is highly welcome! Thank you!

rest:
  - scan_interval: 86400
    resource: "MY API CALL"
    sensor:
      - name: "Solarprognose heute"
        value_template: "{{ value_json.data[0]['value'] }}"
      - name: "Solarprognose morgen"
        value_template: "{{ value_json.data[1]['value'] }}"

Well, well, I figured out an alternative solution which works well. In essence I let the rest sensor pull out the whole array around “data”, and then create two new template sensors where I do some trimming/cutting of characters:

Rest configuration:

rest:
  - scan_interval: 86400
    resource: MY API CALL
    sensor:
      - name: solarprognose_heute_morgen_raw
        value_template: "{{ value_json.data }}"

Template sensors cutting/trimming/splitting the string:

sensors:

  - platform: template
    sensors:
      solarprognose_heute_clean:
        value_template: "{{ states.sensor.solarprognose_heute_morgen_raw.state.split(':')[1][1:-12] | round (1) }}"
        unit_of_measurement: kWh

  - platform: template
    sensors:
      solarprognose_morgen_clean:
        value_template: "{{ states.sensor.solarprognose_heute_morgen_raw.state.split(':')[2][1:-1] | round (1) }}"
        unit_of_measurement: kWh

If it’s always 2 values:

{{ (value_json.data).values() | first }}
{{ (value_json.data).values() | last }}

Or by index

{{ ((value_json.data).values() | list)[0] }}
1 Like

Thank you, that is so much more elegant and less prone to errors. The “first/last” did not work for me, but the list approach did do it.

Thank you Didgeridrew!

1 Like