Is this the only way to use index to get deeply nested children?

Here’s a simplified example of one of the data files I am trying to get information from:

get:
  responses:
    '200':
      content:
        application/json:
          examples:
            example-1:

Is this really the only way? It’s so… ugly.

{{ $example := index (index (index (index (index (index (index $data "get") "responses") "200") "content") "application/json") "examples") "example-1" }}

Your data file is ugly. The way to access is is elegant.

You can pass multiple indices:

{{ $example := index $data "get" "responses" "200" "content" }}
4 Likes

Thanks @wbamberg

1 Like

Also, although this seems to be undocumented, you can pass a slice into index:

{{ $indices := slice "get" "200" "responses" "content"}}
{{ index $thing $indices }}

I’ve found this super-helpful when processing OpenAPI data, because you can convert a $ref, which is given as a URI, into an array (slice), then pass that to index to access an object under .Site.Data.

2 Likes

Hey, thanks again. I’m going to play around with that slice technique, I think it may have helped with an earlier issue I ran into. Solved that with a top down reorganization of my content that wound up being better than I started with, but I’m sure as I get deeper into this project I’ll run into more of the same.

1 Like

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