Skip to main content
Brimham Rocks, Yorkshire, UK

How to use a JSON file as an Astro content collection

This is a new website and is under active development. There will be some odd-looking layouts and colours while this is happening. Please bear with me and check back again to see any updates.

To render Markdown content to HTML, we can use an Astro plugin called [Astro Markdown](<https://github.com/astro-community/md).

To get the best integration, after installing with npm install @astropub/md --save-dev change the astro.config.mjs file to include the Astro Markdown plugin:

import { defineConfig } from 'astro/config';
import markdownIntegration from '@astropub/md'
export default defineConfig({
plugins: [
markdownIntegration(),
]
});

In a .astro file, you can now use the md tag to render Markdown content:

---
import BaseLayout from "@/layouts/BaseLayout.astro";
import { getCollection } from 'astro:content';
import { markdown } from '@astropub/md';
// Get your data collection - this is defined in /src/content/config.ts with a collection type of `data`
// The actual data is in timeline[0].data
const timeline = await getCollection('it-timeline');
---
<BaseLayout frontmatter={pageMeta}>
<ul>
{timeline[0].data.map((decade) => (
<li key={decade.decade}>
<h3>{decade.decade}</h3>
<ul>
{decade.events.map(async (event) => (
<li key={event.year}>
<!-- This is where we are rendering the Markdown to HTML -->
<strong>{event.year}:</strong> {await markdown.inline(event.markdown)}
</li>
))}
</ul>
</li>
))}
</ul>
</BaseLayout>