DEV Community

Cover image for How to generate a complete JSON file with Nunjucks 🎮
Benjamin Rancourt
Benjamin Rancourt

Posted on • Originally published at benjaminrancourt.ca on

How to generate a complete JSON file with Nunjucks 🎮

I am currently in the process of refactoring my website to speed up its generation and I came across an interesting problem: how to generate a JSON file with Nunjucks in Eleventy?

If the object contains only strings , it is really trivial. But, if you add a numeric property and you want to keep its type intact, it is still simple:

{
  "name": "{{ author.name }}",
  "age": {{ author.name }}
}
Enter fullscreen mode Exit fullscreen mode

But, it gets complicated if you want to introduce array properties. Effectively, if you want to have a valid JSON file, the items must be separated by a colon (,) and it starts to look a lot more complex like in the example below:

  {
    {%- if collections.feed.authors -%}
    "authors": [
      {%- for author in collections.feed.authors %}
        {
        "avatar": "{{ author.avatar }}",
        "name": "{{ author.name }}",
        "url": "{{ author.url }}"
        }
      {%- if not loop.last -%},{%- endif -%}
      {%- endfor %}
    ]
    {%- endif -%}
  }
Enter fullscreen mode Exit fullscreen mode

It is not pretty, but it works. 🤕

But what if you want to add a property whose value contains quotes ("), like HTML values? Personally, I tried a lot of ideas, but none worked. 😟

{
  "html": "{{ author.html }}",
  "safe": "{{ author.html | safe }}"
}
Enter fullscreen mode Exit fullscreen mode

I searched the Web and came across an old question on Stack Overflow which has the solution below that worked for me:

{
  "html": {{ author.html | dump | safe }}
}
Enter fullscreen mode Exit fullscreen mode

The combinaison of the dump and safe filters make it possible to render the value exactly as it comes from the source. For an array, this even make it possible to simplify the code for its generation if the objects are already correct:

{
  {%- if authors.tags -%}
    "tags": {{ authors.tags | dump | safe }}
  {%- endif -%}
}
Enter fullscreen mode Exit fullscreen mode

I hope this post helps you get to know the Nunjunks templating language better! 😁

Top comments (0)