javascriptjekyllliquid

How to convert Liquid array to a Javascript array?


In my Jekyll site, I want to load data from _data/stocks.yml and use the data in a Chart.js-powered graph. Chart.js accepts chart datasets and labels as simple Javascript arrays. Is there an easy way to convert a Liquid array to a Javascript array or map?

I tried doing: var months = {{ site.data.stocks.yml | json }} but I think that only works for individual strings/variables and not collection structures.

The _data/stocks.yml file:

- month: Jan '20
  portfolio: '-4.5'
  spy: '-0.16'
- month: Feb '20
  portfolio: '-19.2'
  spy: '-8.41'
- month: Mar '20
  portfolio: '-19.1'
  spy: '-12.51'

Solution

  • I think there are two issues with what you're trying to accomplish.

    The first is that that, according to the jekyll documentation, you should access a data file using the format site.data.datafile without the extension .yml. In your case, you would access your data using {{ site.data.stocks }}

    The second is that the jekyll (liquid) filter for converting to json is | jsonify, not | json. So to convert your stocks data file to json you would use {{ site.data.stocks | jsonify }}