The big difference between JSON feed and XML feed is the ability to read and write JSON. Parsing XML is not an easy task whereas when it comes to JSON, you have to write only a single line of code and use it any way you want. With the advent of JSON-based feed readers, it would be nice to have a JSON feed for your blog.
In this article, you’ll learn to use Jekyll and Liquid syntax to create a JSON feed for your blog.
Contents
Prerequisites
Before proceeding, make sure that:
- Your Jekyll blog is already set up.
- Your blogs live at the
_blogs
directory.
Creating a feed.json File
First, create a feed.json file at the root of your website and add the following front matter to it:
permalink: /blog/feed.json
This will make your blog feed available at the /blog/feed.json
path.
Writing Liquid Code
In the feed.json file, add the following Jekyll code:
{
"version": "https://jsonfeed.org/version/1.1",
"title": {{ 'JSON Feed' | xml_escape | jsonify }},
"description": {{ site.description | jsonify }},
"favicon": {{ '/assets/images/logos/favicons/apple-touch-icon.png' | absolute_url | jsonify }},
"language": "en",
"home_page_url": {{ '/' | absolute_url | jsonify }},
"feed_url": {{ page.permalink | absolute_url | jsonify }},
"user_comment": "This feed allows you to read the blogs from this site in any feed reader that supports the JSON Feed format.",
"items": [{% for blog in site.blogs reversed %}
{
"id": {{ blog.url | absolute_url | jsonify }},
"url": {{ blog.url | absolute_url | jsonify }},
"language": "en",
"title": {{ blog.title | jsonify }},
"summary": {{ blog.description | jsonify }},
"content_html": {{ blog.content | jsonify }},
"date_published": {{ blog.date | date_to_xmlschema | jsonify }},
"date_modified": {{ blog.last_modified_at | date_to_xmlschema | jsonify }},
"image": "{{ blog.image.path }}",
"banner_image": "{{ blog.image.path }}",
"authors": [{{ blog.author | jsonify }}],
"categories": {{ blog.categories | jsonify }},
"tags": {{ blog.tags | jsonify }}
}
{% unless forloop.last %},{% endunless %}{% endfor %}
]
}
The above feed uses the most recent version of JSON Feed specifications.
Adding Feed URL to Head
The final step is to add a reference to your JSON feed in the head tag of your website so that anyone looking for your blog feed can find it out from here.
<link rel="alternate" type="application/json" title="JSON Feed" href="https://www.ravsam.in/blog/feed.json" />
Result
To check the JSON feed, run the following command in your terminal:
bundle exec jekyll serve
Then, check out your feed at http://localhost:4000/blog/feed.json.
You can see a JSON feed created for your blog. You can submit this blog feed to a JSON Feed Reader.
We can also create JSON feeds for podcasts, microblogs, and submit them to content aggregators. As we move into the future, you’ll see more and more blogs migrating to the JSON feed as it is extremely easy to consume and set up.