Configuring file sensor to read json file properly

I have a json.dump file from my pfSense router that displays my firewall rules. What I would like to get out of it is to see the status of a particular rule (enabled/disabled). I can’t seem to find a value_template syntax that would help me extract this (my programming skills are quite basic)

sensor:
  - platform: file
    file_path: /config/python_scripts/pfSense_rules.json
    name: pfSense_rule_office
    value_template: '{{ value_json ????}}'

Dump file example

If the specific rule is {“disabled”: “”} then my rule is, of course, disabled and if this field is missing then it’s enabled. I can differentiate rules eighter by “tracker”: “1542580425”, or by “descr”: “office_pc_on_vpn”

Assuming you’re getting this from some API on the router, you’re probably better off putting the whole thing into a custom component. It could then hit the API to get a list of all rules, create a sensor for each one, and update the enabled/disabled statuses.

Otherwise:

{% set tracker = '1542580425' %}
{% for rule in value_json['rule'] %}
  {% if rule['tracker'] == tracker %}
    {{ 'disabled' not in rule }}
  {% endif %}
{% endfor %}

That should produce “True” (i.e. enabled) for any rule that doesn’t have the “disabled” key.

1 Like

Awesome,

sensor:
   - platform: file
     file_path: /config/python_scripts/pfSense_rules.json
     name: pfSense_rule_office
     value_template: '{% set tracker = "1542580425" %} {% for rule in value_json["rule"] %} {% if rule["tracker"] == tracker %} {{ "disabled" not in rule }} {% endif %} {% endfor %}'

This worked like a charm. You are right about the custom component, I’m gonna have to have a look into that as I ultimately wanted to combine sensor and a script to get a toggle switch for my rule.
I’m barely swimming above water but yeah, will get there soon hopefully.
Thanks again.

FYI, you can do something like (I think) this to have the template multiline and remove the need for the initial quotes:

value_template: >-
    {% set tracker = '1542580425' %}
    {% for rule in value_json['rule'] %}
      {% if rule['tracker'] == tracker %}
        {{ 'disabled' not in rule }}
      {% endif %}
    {% endfor %}

Like I sad, barely swimming :slight_smile: