Render content for all your Jekyll pages as a single JSON endpoint
You have the content of your site stored as Markdown pages, but you want to load each page as structured data. Such as for building a SPA (with React or Vue) or a mobile app.
The JSON Liquid file below uses all pages in the site and renders their content as one file.
The output has key-value pairs, with the page's URL as the key and and the content as plain text (no markdown or HMTL) for the value.
{
"PAGE_URL": "PAGE_CONTENT"
}See sample-data.json below for a more realistic version.
There is a where expression to only include HTML and Markdown pages that are useful. This will filter out pages like feed.xml, robots.txt, sitemap.xml and CSS. As well as the JSON API file itself.
- Copy the content of the JSON file below. (The
.liquidextension is for syntax highlighting as a gist, but just think of it as a.jsonfile.) - Add to your project as JSON file e.g.
data.jsonin your project root. Orapi/data.json. - Start your Jekyll server.
- View the page where your JSON file is served from e.g.
http://localhost:4000/data.json
- Rather than outputting key-value pairs, another approach would be building an array of pages, where each item has the structure:
{ "url": "", "content": ""}. jsonifyis used here to add double quotes around a string, not to actually render an array or hash as a JSON object. Usingjsonifyis safer than manual quotes, as it will handle escaping quotes for you.- We use
markdownifyto convert markdown to HTML, then strip HTML to convert to plain text. - Unfortunately, we can't use Jekyll filters to process Liquid tags
{{ }}or{% %}. So your content will not look so readable if you render it on a webpage. But a custom Jekyll plugin in Ruby could be used to evaluate that before the content is outputted to the JSON file. - See Jekyll cheatsheet
- The sample JSON file below shows output based on running this site locally - MichaelCurrin/jekyll-blog-demo. It's pages are
index.md,about.mdand404.html.
I just used this for a Jekyll migration. Nice one, Michael.