Hi,
I have a json file. It’s called footer-buttons-obj.json
Very simplified it looks like this:
{
"porch": [
{
"icon": "mdi:home",
"background": "aliceblue",
"tap_action": {
"action": "navigate",
"navigation_path": "/porch-control/ac"
}
},
{
"icon": "mdi:lightbulb-outline",
"entity": "light.porch_lights",
"margin": "8px",
"hold_action": {
"action": "navigate",
"navigation_path": "/porch-control/ac"
}
}, ... and lots more
"family": [
{
"icon": "mdi:home",
"background": "aliceblue",
"tap_action": {
"action": "navigate",
"navigation_path": "/porch-control/ac"
}
},
{},
{
"icon": "si:lg",
"size": "48px",
"color": "rgb(165,0,52)",
"tap_action": {
"action": "fire-dom-event",
"include": "../views/porch-tv.yaml",
"options": [
"dismissable: true",
"title: Family Fire TV",
"autoclose: false"
]
}
}, .. and lots more...
I want to import this into a variable in my dashboard - but only import the key I need (i.e. Porch
or Family
).
I tried using the regular import, and I succeeded in importing the whole json file into a variable. But ran into trouble trying to use it as it becomes a weird variable ModuleTemplate
that can’t be iterated.
So then I tried the alternate import syntax, but using this failed (it can’t parse ‘porch’ as a key)
{% from '/config/yaml/imports/footer-buttons-obj.json' import porch as footer_data with context %}
If I change the json file into a yaml file with and assign the json to a variable called porch
in that file like so:
{% set porch = {...all the json data...} %}
Then this works:
{% from '/config/yaml/imports/footer-buttons-obj.yaml' import porch as footer_data with context %}
But I lose all the benefit of a nice clean json file.
So, I came up with the following, which works, with one downside:
{% macro import_json(source) %}
{% include source %}
{% endmacro %}
{% set room = "porch" %}
{% set import_file = '/config/yaml/imports/footer-buttons-obj.json' %}
{% set json_data2 = (import_json(import_file) | fromjson)[room] %}
The downside is that it’s loading the whole darn json file, sending a string back to the import_file
variable, which I then convert to a json object and pluck the key I want.
Can anyone think of a cleaner approach that (a) let’s me use variables for both the filename and key and (b) doesn’t load the whole darn json file?