docs
docs copied to clipboard
Request: Add documentation on how to load data files
I'm coming from both Jekyll and Eleventy, both of which have fairly straightforward ways to load data files (JSON or YAML).
Working with Astro, I can't figure out how this should be done. The questions I've encountered are:
- Should I be using
fetch()
for this? This page seems to indicate thatfetch()
is the preferred way to do this, but there isn't an example reading from a local file. - Should I be using
fs
for this? In other words, should I just use regular-old Node.js functionality when I want to read a data file?
It would be great to add some documentation explaining "the Astro way" of dealing with data files. It would really help for folks like me who are trying to convert an existing Jekyll or Eleventy site to Astro.
Thanks for this, @nzakas! I agree, this would be a helpful addition. In fact, you've already made some of us start to think of things to add ... 😄
Can I ask as a data point, where in our existing documentation would you think to look for this? It would be helpful to know where you might naturally look, or which keywords you might search in order to find this. We have some initial thoughts, but hearing from those coming from other frameworks will also help us as we try to get new content in the easiest-to-find place.
@sarah11918 the very first thing I did was search for "data files", and that brought me to the page about fetch()
that I mentioned above.
An idea: If you renamed "Data Fetching" to "Data Loading", you could cover loading local data files in addition to loading data from external sources like APIs. In my mind, these are just two flavors of the same thing so I would expect info on both to be co-located.
More specifically, if you were to talk about loading both JSON and YAML files, I think that would be a soft landing place for folks coming from Jekyll and Eleventy to get started (assuming I could search for "JSON data files" or "YAML data files" and be brought to the documentation related to local data files).
As a quick answer, Astro has out-of-the-box support for importing .json
, so you can generally do:
---
// src/pages/index.astro
import stats from '../stats.json';
---
{stats.map(stat => <p>The stat is {stat}!</p>)}
I believe import
support for YAML files is also possible but requires a plug-in. Would be great to have a guide showing how to do that as it’s a fairly common request.
Oh nice! Didn’t realize that was possible. That’s certainly a lot easier than the other options.
Update here: we’ve recently updated our imports page to hopefully make this use case easier and are also hoping to add a YAML example there soon as part of https://github.com/withastro/docs/issues/1274. Going to close this as hopefully resolved for now!