LoginSignup
2
2

More than 5 years have passed since last update.

Jekyllでpostsをpluginの力を借りずにJSONに変換

Posted at

はじめに

静的サイトでそこまでやるの?って思われるかもしれませんが、きっと使い道は無いわけではないはず。Jekyllで作っているサイトの為に投稿(posts)をJSONに変換したいのでやり方を調べました。(ソースはこちら"JSONify your Jekyll site")

JSON作成用のJSONを作る

pluginでgeneraterやらconverterやらを使えばおそらく簡単に作れるとは思うのですが、今回はpluginを使わずに変換する方法です。Github Pagesでも使えるはず(?)です。まず流用元は以下のようなコードになっています。

---
layout: nil
---

[
{% for post in site.posts %}
    {
      "title"    : "{{ post.title }}",
      "url"     : "{{ post.url }}",
      "date"     : "{{ post.date | date: "%B %d, %Y" }}",
      "content"  : "{{ post.content | escape }}"
    } {% if forloop.last %}{% else %},{% endif %}
{% endfor %}
] 

これをそのまま使ってもエラーが出てしまいました(バージョンの違いのせい?)。それに加えて「content」までは必要なかったっていうのとどちらかというと「tags」情報がほしかったので以下に書き換え。

---
---

[{% for post in site.posts %}{
"title":"{{ post.title }}",
"url":"{{ post.url }}",
"date":"{{ post.date | date: "%B %d, %Y" }}",
"tags":[{% for tag in post.tags %}"{{ tag }}"{% if forloop.last %}{% else %},{% endif %}{% endfor %}]
}{% if forloop.last %}{% else %},{% endif %}{% endfor %}]

汚い!すごく汚いですね。けど、この文法にしないと出力されたJSONに無駄に改行とかがまぎれこんでしまうのでやむを得ず。。。(もっと綺麗に書ける方法を知っている方がいましたらご教示願いますm(__)m)
以下、_sites配下に出力されたJSONです。

[{
"title":"たいとる",
"url":"path/to/post.html",
"date":"January 11, 2015",
"tags":["たぐ1","たぐ2"]
}]

このJSONを使って何かしらのスクリプトが書けそうです。

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2