Output a JSON file with Jekyll

14 Mar 2025 in TIL

I needed to expose some of the data we had in app/_data in our Jekyll deployment for consumption in another project. Instead of copy/pasting the data, I chose to expose it as an API.

To do the same, create a file named app/_plugins/your_name_here_hook.rb with the following contents:

ruby
module MyApi
def self.process(site)
api_prefix = 'api'
the_data = site.data['path_to']['your']['data']
FileUtils.mkdir_p("#{site.dest}/#{api_prefix}")
File.write("#{site.dest}/#{api_prefix}/your-data.json", the_data.to_json)
end
end
Jekyll::Hooks.register :site, :post_write do |site, _|
MyApi.process(site)
end

Then you can access /api/your-data.json on your Jekyll deployment to see the data.