简体   繁体   中英

Sort JSON array on Jekyll

I'm working on a Jekyll project and have tools.json in the _data folder. The JSON file is formatted like so:

{
"tools": [
    {
        "title": "DER tool",
        "url": "https://der.us/",
        "sticky": "false"
    },
    {
        "title": "ZXY tool",
        "url": "https://zxy.us/",
        "sticky": "false"
    },
    {
        "title": "ABC tools",
        "url": "https://abc.us/",
        "sticky": "false"
    },
    {
        "title": "RSW tools",
        "url": "https://rsw.us/",
        "sticky": "true"
    }
]}

I want to sort the items alphabetically, but if sticky: true it should be on the top. Ideally the output should be like:

<ul>
<li>RSW tool</li>
<li>ABC tool</li>
<li>DER tool</li>
<li>ZXY tool</li>
</ul>

You can sort the sticky and non-sticky items separately.

{% assign sticky_tools = site.data.tools.tools | where: 'sticky', true | sort: 'title' %}
{% assign tools = site.data.tools.tools | where: 'sticky', false | sort: 'title' %}

<ul>
    {% for t in sticky_tools %}
    <li>{{ t.title }}</li>
    {% endfor %}

    {% for t in tools %}
    <li>{{ t.title }}</li>
    {% endfor %}
</ul>

As an aside, if you have tools.json containing just the array at the root (wthout the "tools" key), you can access it with site.data.tools instead of site.data.tools.tools .

You can do successive sorting.

{% assign sortedByTitleTools = site.data.tools.tools | sort: "title" | reverse %}
{% assign sortedByStickyTools = sortedByTitleTools | sort: "sticky" | reverse %}
<ul>
{% for t in sortedByStickyTools %}
  <li>{{ t.title }}</li>
{% endfor %}
</ul>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM