[英]Sort JSON array on Jekyll
I'm working on a Jekyll project and have tools.json
in the _data
folder. 我工作的一个化身项目,并
tools.json
在_data
文件夹中。 The JSON file is formatted like so: JSON文件的格式如下:
{
"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. 我想按字母顺序对项目进行排序,但如果有
sticky: true
则应位于顶部。 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
. 顺便说一句,如果您的tools.json仅在根目录包含数组(没有“ tools”键),则可以使用
site.data.tools
而不是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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.