Ognjen Regoje bio photo

Ognjen Regoje
But you can call me Oggy


I make things that run on the web (mostly).
More ABOUT me and my PROJECTS.

me@ognjen.io LinkedIn

Generate JSON files in Jekyll

#jekyll

I must admin I got nerd sniped by this question on Reddit asking how to generate JSON in Jekyll but I’m happy to say that it’s actually relatively simple.

Here’re the steps with a new collection.

Create the collection folder, in my case, _j.

Create a new document in the collection, in my case _j/test.md:

---
layout: j
name: Test name
---

Not needed

Note that you have to have some content otherwise Jekyll wont write the file.

In _layouts create j.json that has the JSON structure that you want:

{
  name: "{{page.name}}"
}

In config.yml set the collections output to true:

  j:
    output: true

At this point the JSON content will be rendered in localhost:4000/j/test and localhost:4000/j/test/index.html.

Next, create a new file in the _plugins folder, called json.rb with the following content:

require 'fileutils'
module Filter
  def self.process(site, payload)
    site.collections['j'].docs.each do |x|
      f = x.destination("")
      new_destination = f.split("/")[0..-3].join("/") + "/#{x.data['slug']}.json"
      FileUtils.cp f, new_destination
    end
  end
end

Jekyll::Hooks.register :site, :post_write do |site, payload|
  Filter.process(site, payload)
end

This creates hook that runs when Jekyll is done writing files. Jekyll will write _site/j/test/index.html. This hook will then take that file and copy it to _site/j/test.json. At this point the file is available on localhost:4000/j/test.json.

If you’d like to do it with an existing collection, then you should first follow the steps for publishing a linked folder in Jekyll first but change posts to the name of your collection (j) in the example above. After you’ve set that up, follow the steps above.