Dynamically query a json file

Hiii.

This is an example json file:

{
    "database": {
		"house": {
            "square": 100,
            "hight": 5,
            "doors": 2,
            "windows": 5
        },
        "garage": {
            "square": 20,
            "hight": 2.5,
            "doors": 1,
            "windows": 1
        },
        "office": {
            "square": 150,
            "hight": 3,
            "doors": 2,
            "windows": 5
        }
    }
}

saved as measurement.json in www folder of home assistant.

I’ve input_select.choice:

  • house
  • garage
  • office

My goal is to create 4 sensors:
sensor.square
sensor.hight
sensor.doors
sensor.windows
that take the result from the json file based on the property chosen with the input_select.

If possible, I would prefer to keep a database somewhere in my system because:

  • more automations could access the data;
  • the database is complex and subject to frequent changes that cannot be done at sensor level.

Thanks

Possibly a template sensor, I would likke to knmow how to do this too

Possible solution:

  1. Load the db into an attribute through a command_line sensor (states have a 255 char limit, which attributes haven’t):
command_line:
  - sensor:
      name: json_db
      command: cat /config/database.json
      value_template: "{{ 'OK' }}"
      json_attributes:
          - database
  1. Have template sensors to extract the proper value based upon the input_select:
template:
  - sensor:
    - name: "JSON db test square"
      state: "{{ state_attr('sensor.json_db', 'database')[states('input_select.json_select')]['square']}}"  

Thanks for your attention:

command_line:
  - sensor:
      name: json_db
      command: cat /config/**measurement**.json
      value_template: "{{ 'OK' }}"
      json_attributes:
          - database

This crete the sensor json_db with state “OK” and with attrib the full content of measurement.json file

template:
  - sensor:
    - name: "JSON db test square"
      state: "{{ state_attr('sensor.json_db', 'database')[states('**input_select.choice**')]['square']}}"

Create the sensor: JSON db test square with state:unavailable.

P.S. ** correct code based on my initial request

If you’re running HAOS, it might be the file is at “/homeassistant”, I don’t remember what’s the root there

The command_line working fine.

Is the data extraction to json failed…

You lack a quote after “states(”, but I guess it’s a typo in the post?

Correct the post… deleted when I added the asterisks!

Yeah. I tested it so definitely works for me.
Try it in the template editor and check what it says…

Thanks for your help!!!