2016-12-07 64 views
0

我正在研究一个名为people.json的文件夹中的Jekyll项目。 JSON文件的格式是像这样:Jekyll`_data/people.json`数组:重组和排序

{ 
    "name" : "George Michael", 
    "topics" : ["Egg", "Cousins"], 
    "contact" : [ 
     { 
      "email" : "[email protected]", 
      "twitter" : "@name" 
     } 
    ] 
}, 
{ 
    "name" : "Tobias", 
    "topics" : ["Analyst", "Therapist"], 
    "contact" : [ 
     { 
      "email" : "[email protected]", 
      "twitter" : "@name" 
     } 
    ] 
} 

我想什么做的是建立一个标签列表不爽,使用topics信息。我曾尝试:

{% for tag in site.data.people %} 
<li> 
    {{ tag.topics }} 
</li> 
{% endfor %} 

将返回:

<li>EggCousins</li> 
<li>AnalystTherapist</li> 

理想情况下,我想返回的标记是:

<li>Analyst</li> 
<li>Cousins</li> 
<li>Egg</li> 
<li>Therapist</li> 

我一直拖网液体文档,并我想我可以通过循环并将它们分解为一个新阵列,并使用split,然后应用一个sort,但实际上这样做的方式完全没有办法。

任何帮助将不胜感激。谢谢。

回答

0

首先,你的JSON是无效的。我的jekyll似乎更喜欢:

[ 
    { 
     "name" : "George Michael", 
     "topics" : ["Egg", "Cousins"], 
     "contact" : [ 
      { 
       "email" : "[email protected]", 
       "twitter" : "@name" 
      } 
     ] 
    }, 
    { 
     "name" : "Tobias", 
     "topics" : ["Analyst", "Therapist"], 
     "contact" : [ 
      { 
       "email" : "[email protected]", 
       "twitter" : "@name" 
      } 
     ] 
    } 
] 

不过,我觉得这个解决方案相当不错。请注意,第一个for循环应该创建一个没有重复的主题数组。

{% comment %}Create an empty array for topics{% endcomment %} 
{% assign topics = "" | split: "/" %} 

{% for author in site.data.people %} 
    {% for topic in author.topics %} 

    {% comment %} As we don't want duplicates in our "topics" list we test it {% endcomment %} 
    {% if topics contains topic %} 
     {% comment %} Do nothing. Could have used unless, but I find if else more expressive. {% endcomment %} 
    {% else %} 
     {% assign topics = topics | push: topic %} 
    {% endif %} 

    {% endfor %} 
{% endfor %} 

Here you have a nice list which you can loop in : {{ topics | inspect }} 
+0

谢谢,这很完美! – mradamw

0

尝试这种解决方案:

{% for tag in site.data.people %} 
    {% for item in tag %} 
    <li> 
     {{ item }} 
    </li> 
    {% endfor %} 
{% endfor %}