Range where $index == $var

How should I go about limiting results from range based on index? So for example, just the result with index of 2. My attempts have lead to undefined variable: $index.

{{ range $index, $element := where $myAPI $index eq $var }}

$myAPI uses getJSON. $var represents the desired index to be used (e.g 2) - this value will derive from front-matter.

Am curious, why do you need range if you’re only returning one item?

Maybe I don’t… Is there another / a better way of getting one item from a (JSON) array?

Yes. If you share your code we can help show you the better way. Or at least an example of your JSON file.

Not sure what code beyond the above would be useful. The JSON is a pretty typical API response, but I’ll include a simplified example below.

{
   "project":{
      "modules":[
         {
            "id":123,
            "thing":{
               "key":"value one"
            }
         },
         {
            "id":258,
            "thing":{
               "key":"value two"
            }
         },
         {
            "id":381,
            "thing":{
               "key":"value three"
            }
         }
      ]
}

modules in this example would be the bit I was ranging over.

I saved your JSON file (with a small syntax fix) to a new hugo site at data/myApi.json then used this template code to get the 2nd index. You can adapt it to your needs:

{{ $json := site.Data.myApi }}
{{ $index2 := index $json.project.modules 2 }}

That works, thanks :slight_smile: Where should I have been looking to find that syntax?

:slight_smile:
See https://gohugo.io/functions/index-function/