0

I have a json file called values.json with different atributes:

{
    "key1": "value1",
    "key2": "value2",
    "key3": "value3"
}

Using Jinja2, I am trying to import it and get just value1, but i don't find the way of doing it. I manage to import all the json and print it in a file called test.j2:

{%- import "./values.json" as values -%}
{{ values}}

but I don't know how to get only the value of key1. I am trying to convert first the file to json and then get the value:

{%- import "./values.json" as values -%}
{% set values_json = values | string | tojson %}
{{ values_json.key1 }}

But I get an empty response. Do you know how I should do it?

The command I use to test it is jinja2 test.j2

pcampana
  • 2,413
  • 2
  • 21
  • 39

1 Answers1

0

import feature is about "Jinja supports putting often used code into macros. These macros can go into different templates and get imported from there." more info here. Seems its not about importing a file as a variable.

I can tell you are running jinja2-cli (jinja2 test.j2). From its documentation one option to load a json file with variables and passing it to the template is by running:

jinja2 test.j2 values.json --format=json

and your template will be able to access the key1, key2, key3 variables directly.

test.j2:

{{ key1 }}
{{ key3 }}
{{ key2 }}

prints:

value1
value3
value2
ilias-sp
  • 6,135
  • 4
  • 28
  • 41