William Boman
William Boman

Reputation: 2227

Jekyll print custom JSON string from data

Let's say I have an array of hashes like so;

site.foo = [
  {
    "foo": "bar",
    "baz": ["a", "b", "c"]
  },
  {
    "foo": "baz",
    "baz": ["x", "y"]
  },
  ...
]

I want to get all values (bar, a, b, c, baz, x, y) in an array and output it as JSON in a javascript variable in a template.

How would I do this?

Upvotes: 0

Views: 665

Answers (1)

David Jacquel
David Jacquel

Reputation: 52829

I assume that you know how your datas are organized.

{% assign splitMark = "###" %}
{% assign arr = "" %}

{% for el in site.foo %}

    {% assign arrSize = arr | size %}

    <!-- if we already have something in our string
         add the splitMark at the end -->
    {% if arrSize > 0 %}
        {% capture arr %}{{arr}}{{splitMark}}{%endcapture%}
    {% endif %}

    <!-- array + foo.foo value + splitMark -->
    {% capture arr %}{{arr}}{{el.foo}}{{splitMark}}{%endcapture%}

    <!-- transform an array to a string
    with elements delimited by splitMark -->
    {% assign bazStr = el.baz | join: splitMark %}

    <!-- array + transformed array -->
    {% capture arr %}{{arr}}{{bazStr}}{%endcapture%}

{% endfor %}

<!-- transform our string to an array splitting at the splitMark -->
{% assign arr =  arr | split: splitMark %}

<script>
    var my_var = {{ arr | jsonify }};
</script>

If you don't know your exact data structure, eg:

  -
    foo: "bar"
    baz: ["a", "b", "c", 10]
  -
    foo: baz
    baz: ["x", "y"]
    any: other
    key: ['toto','titi']

You have to go the plugin way. Create a file _plugins/flatten.rb containing :

module Jekyll
  module FlattenArray
    def flatten( datas )

      datas.flat_map(&:values).flatten

    end
  end
end

Liquid::Template.register_filter(Jekyll::FlattenArray)

You can now flatten your datas like this :

var my_var = {{ site.foo | flatten | jsonify }};

Upvotes: 1

Related Questions