How can I generate a JSON file from my content? #3947
-
|
Say I have this structure: Where a.md contains: ---
title: A
description: This is a test.
---
Blah blah blah...And b.md contains: ---
title: B
description: This is another test.
---
Yadda yadda...I want to output: Where data.json contains: [
{"title": "A", "description": "This is a test."},
{"title": "B", "description": "This is another test."}
]My first idea was to add a collection: eleventy.addCollection('notes', function (collections) {
return collections.getFilteredByGlob('content/notes/*.md');
});Then add this file to content/notes/data.json (based on this guide): [
{% for note in collections.notes %}
{
"title": "{{ note.title }}",
"description": "{{ note.description }}"
}{% unless @last %},{% endunless %}
{% endfor %}
]But the JSON file doesn't end up in the _site directory. Is there a better way? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
|
Edited as I'm not sure which template language you're using. Thought it was You're on the right track. The issue is that you're adding your source file Instead rename it to You'll also want to add a permalink to the front matter of your template. This defines where the file is written out to and importantly allows you to set content/notes/data.njk ---
permalink: /content/notes/data.json
---
[
{%- for note in collections.notes %}
{
"title": "{{ note.title }}",
"description": "{{ note.description }}"
}{% if not loop.last %},{% endif %}
{% endfor -%}
]Note the |
Beta Was this translation helpful? Give feedback.
Edited as I'm not sure which template language you're using. Thought it was
liquidbut that doesn't have@lastYou're on the right track. The issue is that you're adding your source file
content/notes/data.jsonas a.jsonfile..jsonfiles are not considered template files and by default will not be processed.Instead rename it to
content/notes/data.njkso it becomes a template file and will be processed. You can use any template language you like, but I know Nunjucks so the code below should work.You'll also want to add a permalink to the front matter of your template. This defines where the file is written out to and importantly allows you to set
.jsonas it's file extension. If you d…