GroupBy for JSON

I’m listing data from a JSON file on my page. It goes something linke this:

{{ $list := getJSON "blabla.json" }}
{{ range $list.conferences }}
<p>{{ .title }}, {{ .date }}, {{ .country }}</p>
{{ end }}

Now I want to group the conferences by date. This is because I want to put a new <h3> headline for every year. I tried

{{ range $list.conferences.GroupBy "country" }}

but got the error can’t evaluate field GroupBy in type interface {}. (same for GroupByParam)

Is there any way to group JSON data with Go templates?

I think there is no such function to group custom data excepts pages. You could group it via .Scratch manually.

But I think it could be simply achieved by sort.

{{ $list := getJSON "https://mocki.io/v1/fc75575a-bdb1-4712-b49c-fc725538a257" }}
{{/* asc or desc */}}
{{ $sorting := "asc" }}
{{ $year := "" }}
{{ range sort $list.conferences "date" $sorting }}
  {{/* Check if the item year is same as previous item. Generate the new heading if not equals. */}}
  {{ $itemYear := (time .date).Format "2006" }}
  {{ if ne $year $itemYear }}
    {{ $year = $itemYear }}
    <h3>{{ $year }}</h3>
  {{ end }}
  <p>{{ .title }}, {{ .date }}, {{ .country }}</p>
{{ end }}

You may need to adjust the year formatting, it depends on how the format of date looks like.

3 Likes

Thanks, that works!

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.