Rest sensor json attributes/value_template help wanted

Help wanted forming correct rest sensor in configuration.yaml

rest:
  - resource: https://www.samsclub.com/api/node/vivaldi/browse/v2/clubfinder/list?distance=3&nbrOfStores=1&singleLineAddr=Raleigh,%20NC
    scan_interval: 15
    sensor:
      - name: "Sam's Regular Gas"
        json_attributes_path: "$.[0].gasPrices"
        value_template: "{{ value_json[0].price }}"
      - name: "Sam's Premium Gas"
        json_attributes_path: "$.[0].gasPrices"
        value_template: "{{ value_json[0].price }}"

I kept getting this error

Logger: homeassistant.helpers.entity
Source: helpers/entity.py:1205
First occurred: 12:00:09 AM (12 occurrences)
Last logged: 12:00:24 AM

Failed to set state for sensor.sam_s_regular_gas, fall back to unknown
Failed to set state for sensor.sam_s_premium_gas, fall back to unknown
Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 1205, in _async_write_ha_state
    hass.states.async_set(
  File "/usr/src/homeassistant/homeassistant/core.py", line 2302, in async_set
    state = State(
            ^^^^^^
  File "/usr/src/homeassistant/homeassistant/core.py", line 1773, in __init__
    validate_state(state)
  File "/usr/src/homeassistant/homeassistant/core.py", line 239, in validate_state
    raise InvalidStateError(
homeassistant.exceptions.InvalidStateError: Invalid state with length 179311. State max length is 255 characters.

The json_attributes_path does not affect the value_template. Try this (updated to scanning every 15 minutes):

rest:
  - resource: https://www.samsclub.com/api/node/vivaldi/browse/v2/clubfinder/list?distance=3&nbrOfStores=1&singleLineAddr=Raleigh,%20NC
    scan_interval: 900
    sensor:
      - name: "Sam's Regular Gas"
        value_template: "{{ value_json[0]['gasPrices'][0]['price'] }}"
      - name: "Sam's Premium Gas"
        value_template: "{{ value_json[0]['gasPrices'][1]['price'] }}"

Thanks Troon!

No longer getting any errors relating to length, but the sensor still says “Unknown”.

Try using:

value_template: "{{ value[:250] }}"

temporarily, to see what response you are getting from HA’s request.

It may be that the site is browser-sniffing, or you may have made too many requests. The template is correct:

1 Like