Data & content · Lesson 9 of 22 · 15 min
Import data from JSON files
Keep content in JSON, import it into a page, and render it with a Card component.
Services change. Prices change. You don’t want to dig through HTML every time. Put the data in a JSON file and let a component render it.
1. Create the data file
Make a src/data/ folder and add services.json:
src/data/services.json
[
{
"title": "Dinner Parties",
"description": "A seasonal family-style menu for 8 to 20 guests, cooked in your kitchen.",
"price": "From $45 / guest"
},
{
"title": "Weekly Meal Prep",
"description": "Five ready-to-heat meals dropped off every Sunday.",
"price": "From $120 / week"
},
{
"title": "Cooking Classes",
"description": "Hands-on group classes. You cook, we teach, everyone eats.",
"price": "From $60 / person"
}
]
2. Make a Card component
src/components/Card.astro
---
interface Props {
title: string;
description: string;
price?: string;
}
const { title, description, price } = Astro.props;
---
<article class="card">
<h3>{title}</h3>
<p>{description}</p>
{price && <p class="price">{price}</p>}
</article>
<style>
.card {
background: var(--color-card);
border-radius: var(--radius);
padding: 1.5rem;
box-shadow: 0 1px 3px rgb(0 0 0 / 0.08);
}
h3 {
margin-top: 0;
}
.price {
font-weight: 700;
color: var(--color-accent);
margin-bottom: 0;
}
</style>
{price && ...} only renders the price line if there is one.
3. Import the JSON and loop
You import JSON exactly like a component. Astro parses it into a regular JavaScript array.
src/pages/index.astro
---
import BaseLayout from '../layouts/BaseLayout.astro';
import Section from '../components/Section.astro';
import Card from '../components/Card.astro';
import services from '../data/services.json';
---
<BaseLayout title="Home">
<!-- hero stays the same -->
<Section id="services" title="Services">
<p slot="intro">Pick the one that fits your week.</p>
<div class="grid">
{services.map((service) => (
<Card
title={service.title}
description={service.description}
price={service.price}
/>
))}
</div>
</Section>
</BaseLayout>
Add a grid to the page’s <style> block:
.grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
gap: 1.25rem;
}
auto-fit with minmax gives you three columns on a laptop and one on a phone, with no media queries.
4. Move the nav links to JSON too
Same idea, applied to the nav. Create src/data/nav.json:
src/data/nav.json
[
{ "label": "Home", "href": "/" },
{ "label": "About", "href": "/about" },
{ "label": "Blog", "href": "/blog" }
]
Then in Nav.astro, delete the links array and import it instead:
src/components/Nav.astro
---
import links from '../data/nav.json';
const currentPath = Astro.url.pathname;
// isActive() stays the same
---
Nothing else changes. That’s the payoff of separating data from markup.