Iterate a json file object with a sensor

I am very new to Home Assistant and are struggling with coding in jinja / home assistant.

OK, anyway, I am trying to iterate over a json file that contains an object of date-stamps YYYYMMDD each with an array that determines the types for that day.

This is actually a bin collection schedule, and on certain days, certain types of rubbish will be collected, here’s what I have:

This is an extract of the json file:

  "20220509": [ "GARDEN" ],
  "20220514": [ "RECYCLING", "REFUSE" ],
  "20220519": [ "RECYCLING" ],
  "20220523": [ "GARDEN" ]

And this is my sensor code:

- platform: file
  name: Bin Collection
  file_path: /config/bins.json
  value_template: >-
    {% for i in value_json %}
    {% if value_json[i] == now().strftime('%Y%m%d') %}
      {% for t in value_json[i] %}
      {% endfor %}
    {% endif %}
    {% endfor %}

What I am expecting is that if the YYYYMMDD matches today’s date, then the types of collection will be outputted as the sensor state.

Is my approach correct ? - I have not found any examples that do a similar thing to what I am trying to achieve.

Any help would be appreciated

OK, seems that this cannot be done with a local file, as the file sensor only reads the last line of the file.

So this will have to be done with a rest-sensor, which is not so good as my local json file has 1 year of data in it, and it’s just not necessary to make frequent requests.

- platform: rest
  name: bindays
  resource: ""
  method: "GET"
    hours: 24
  value_template: >-
    # {% set today = now().strftime('%Y%m%d') %}
    {% set today = '20220604' %}
    {% if value_json[today] %}
    {% for i in value_json[today] %} 
    {% endfor %}
    {% endif %}

So this will provide a sensor state of for example # RECYCLING REFUSE - but why has the ‘#’ comment been added to it, and what is the best method of setting the output state so that I can use this data to for example trigger a notify event ?

How can I set the state to be an object with for example:


Assuming the value_json is a dict, this is the simplest output

value_template: "{{ (value_json.get(now().strftime('%Y%m%d')) or []) | join(', ') }}"

You may want to look at this thread. You could use jq and not rest.