Home > front end >  Access specific data from CSV file in Jekyll
Access specific data from CSV file in Jekyll

Time:01-21

I wish to access/query specific data from a CSV file in Jekyll (liquid). My CSV file has the name planets.csv and it's like this:

name, Mercuy, Venus, Earth, Mars
satellites, 0, 0, 1, 2
diameter, 0.38, 0.95, 1.00, 0.53

Let's say I want to get the mean diameter of Mercury. I'm trying this examples:

{{ site.data.planets.diameter[1] }}
{{ site.data.planets.diameter['Mercury'] }}

Since my data is like a table, I'm not sure how to handle it. I even tried splitting the data planet by planet into YML files (i.e., Mercury.yml):

---
- name: Mercury
  satellites: 0
  diameter: 0.38

So this syntax should work...

{{ site.data.Mercury.diameter }}

CodePudding user response:

{{ site.data.planets.Mercury.diameter }}

Would work on a dictionary:

Mercury:
  satellites: 0
  diameter: 0.38

And this is probably the best way to query the data as you need it.

So, you would have the YAML:

Mercuy:
  satellites: 0
  diameter: 0.38
Venus:
  satellites: 0
  diameter: 0.95
Earth:
  satellites: 1
  diameter: 1.00
Mars:
  satellites: 2
  diameter: 0.53

And if you want to keep this in a CSV, what you could do is:

name, satellites, diameter
Mercury, 0, 0.38 
Venus, 0, 0.95 
Earth, 1, 1.00 
Mars, 2, 0.53

And then, use a where filter:

{{ (site.data.planets | where:"name","Mercury")["diameter"] }}

Now, for the sake of completeness, if you want to access Mercury data on:

- name: Mercury
  satellites: 0
  diameter: 0.38

You would need to access it via:

{{ site.data.planets[0].diameter }}
  •  Tags:  
  • Related