Output JSON in Jekyll

Episode #19 - May 17, 2016 - 4 minutes

Sometimes it’s useful to output front matter or Collection data as JSON so we can reference it in Javascript.

If the data is an array or hash you can use the jsonify filter.

---
colors:
  - red
  - blue
  - green
---
<script>
  var colors = {{ page.colors | jsonify }};
</script>

Which generates a JSON array of colors.

...
var colors = ["red","blue","green"];
...

If we need more control over the output we can always build a JSON object ourselves.

var posts = [
  {% for post in site.posts %}
    {
      "title": "{{ post.title }}",
      "category": "{{ post.category }}",
      "url": "{{ post.url }}"
    }
    {% unless forloop.last %},{% endunless %}
  {% endfor %}
];

This gives us complete control over the JSON and allows us to run variables through filters.

[
  {
    "title":"Where Did The Cookie Come From",
    "category":"Information",
    "url":"/information/2016/01/02/where-did-the-cookie-come-from.html"
  },
  {
    "title":"What Is Sour Dough",
    "category":"Information",
    "url":"/information/2016/01/01/what-is-sour-dough.html"
  }
]

Katy DeCorah shows us a real application of this technique in her JekyllConf 2016 talk, Unconventional Use Cases For Jekyll.

Katy creates a map which shows the location of all the speakers at the conference. Hovering over a country displays the speakers in that country.

JekyllConf 2016 map

It’s all controlled by a Jekyll data file which is output to JSON.

- speaker: Ire Aderinkokun
  twitter: ireaderinokun
  country: Nigeria
  talk: Using Jekyll For Rapid CSS Testing

- speaker: Amy Johnston
  twitter: amybeukenex
  country: Netherlands
  talk: Jekyll For Technical Documentation

- speaker: Julio Faerman
  twitter: jmfaerman
  country: Brazil
  talk: Jekyll On AWS

- speaker: Bud Parr
  twitter: budparr
  country: United States
  talk: Real World Content Strategy With Jekyll
...

The code for the site is available here.