Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load data from JSON in Jekyll

Tags:

json

jekyll

While exploring Jekyll for site generation I faced with a JSON data loading problem. I've generated default Jekyll site, added tracks.json file to _data folder and added this code to default index.html

<span>Tracks:</span>
<ul>
  {% for track in site.data.tracks.tracks %}
    <li>Title: {{ track.title }}</li>
  {% endfor %}    
</ul>

In a result I've got this code generated:

<span>Tracks:</span>
<ul>
</ul>

tracks.json looks like:

{
   "tracks":[
      {
         "id":"140",
         "title":"Android"
      },
      {
         "id":"142",
         "title":"GDG[x]"
      }
   ]
}

Am I using the right way to access JSON fields? If not, what is the right way?

UPDATE: issue was fixed in Jekyll v.2.1.0

like image 924
zasadnyy Avatar asked Jun 01 '14 19:06

zasadnyy


Video Answer


2 Answers

You can make your top-level element in the .json file an array like this:

[{
  "id":"140",
  "title":"Android"
},
{
  "id":"142",
  "title":"GDG[x]"
}]

Then you can access it more simply like this {% for track in site.data.tracks %}.

like image 69
Terry Roe Avatar answered Oct 19 '22 02:10

Terry Roe


Try it by site.data.tracks[0].tracks. Have a good time. ;-)

like image 3
Ourai Lin Avatar answered Oct 19 '22 03:10

Ourai Lin