Range last n entries of JSON data file

I have following code to show all entries in a JSON data file (/data/signatures/signatures.json):

{{ range .Site.Data.signatures }}
  {{ range sort . "id" "desc" }}
     <tr>
        <td>{{ .name }}</td>
     </tr>
  {{ end }}
{{ end }}

How can I only show the last n entries in this data file?

I tried last 10 .Site.Data.signatures but got can't iterate over map[string]interface {}. Thank you for your help!

The data files looks like this:

[
  {
    "name": "Oldest",
    "id": 0
  },
  {
    "name": "Second",
    "id": 1
  },
  {
    "name": "Newest",
    "id": 2
  }
]

Look here:

Could you please help with my specific example? When doing {{ range last 10 .Site.Data.signatures }}, I get

error calling last: can't iterate over map[string]interface {}

Is it because I use a JSON file?

Please allow me to push this issue. I’m sure the solution isn’t hard…

Thanks to a helping hand, the issue is solved now. Since my constellation is a bit more complicated (additional if condition) I’ll post my current code which is different from the snippet I posted in the first post.

The main lessons I learnt:

  • Loading a JSON file into a variable makes things easier. By this I can already apply conditions (display only those with “permissionPub” = “yes”)
  • first and last can be easily applied as function to a range sort command. In the first post this would already have been possible in line 2 but then the condition wasn’t working as I wanted
{{ $json := getJSON "data/signatures/signatures.json" }}
{{ $json := where $json "permissionPub" "yes" }}

{{ range sort $json "timestamp" "desc" | first 10 }}
   <tr>
      <td>{{ .name }}</td>
   </tr>
{{ end }}
1 Like