Skip to content

Conversation

@jmooring
Copy link
Member

Closes #8859

With a CSV file like this:

"name","type","breed","age"
"Spot","dog","Collie",3
"Rover","dog","Boxer",5
"Felix","cat","Calico",7

You can now do this:

{{ $opts := dict "toMap" true }}
{{ with resources.Get "pets.csv" | transform.Unmarshal $opts }}
  <ul>
    {{ range where . "type" "dog" }}
      <li>{{ printf "My %s %s is a %s" .type .name .breed }}</li>
    {{ end }}
  </ul>
{{ end }}
@moorereason
Copy link
Contributor

Looks good, @jmooring. I implemented this same solution recently for a project I'm working on. I was going to show up out of nowhere and fix a 5-year old feature request, but you beat me to it! 😆


// Whether to unmarshal to a map instead of an array. Used in the CSV
// decoder. Default is false.
ToMap bool
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I suggest we make this an enum, e.g. targetType (slice, map - default slice).

I'm pretty sure we at one point will get more options here (e.g. the new Go iterator types).

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've made the change. Note that targetType is still a CSV-specific option.

@bep bep merged commit db72a1f into gohugoio:master Apr 21, 2025
6 checks passed
@jmooring jmooring deleted the csv-to-map-8859 branch April 21, 2025 17:40
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

3 participants