How to convert Jekyll data into JSON

Recently, I was given a task to extract that data out of Jekyll site so I can than move it into MongoDB.

The first step I took was to create a file called, _pages/api-posts.html.

Jekyll uses an HTML templating tool called, Liquid template.

Liquid templates allow you to add logic into your HTML file, and it will compile into plain HTML.

For example,



{% assign fruits = ["oranges", "apples", "peaches"] %}


{% for fruit in fruits  %}
  <div>
    I like {{ fruit }}
  </div>
{% endfor %}

And the output would be


<div>
  I like oranges
</div>
<div>
  I like apples
</div>
<div>
  I like peaches
</div>

In my api-posts.html file, I’m going to use Liquid template to build my JSON like output.


---
title: List of all posts
permalink: /api/posts
---
[
  {% for post in site.posts %}
    {
      "date": "{{ post.date }}",
      "title": "{{ post.title }}",
      "content": "{{ post }}",
      "tags": "{{ post.tags | jsonify }}",
      "categories": "{{ post.categories | jsonify }}",
      "url": "{{ post.url }}",
      "slug": "{{ post.slug }}"
    }
    {% unless forloop.last %},{% endunless %}
  {% endfor %}
]

I go over all the site.posts in a for-loop, and then extract the date, title, content, tags, categories, URL, and slug into the JSON like output.

You can build your JSON like structure how ever you’d like. In the example above this is what mine will look like.


[
  {
    "date": "2014-01-01T23:28:56.782Z",
    "title": "Why I like fluffy cats",
    "content": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae",
    "tags": ["fluffy", "sassy"],
    "categories": ["friendly", "cute"],
    "url": "/2014/01/01/fluffy-cats",
    "slug": "fluffy-cats"
  },
  ...Other posts
]

The next step is to run jekyll build to build the output above.

Jekyll will create the JSON output but in a HTML file. To make it a JSON file, we just need to rename the file with a little bit of terminal command.


mv ./_sites/api-posts.html ./posts.json

That’s it!

By using liquid template you can output JSON structure however you like and migrate the Jekyll site to another platform.

I like to tweet about code and post helpful code snippets. Follow me there if you would like some too!