Group data from CSV file

hi there,
i think this is what exactly what i need. however, my GroupBy Data is in the row of a .csv file. I tried to adjust your code to make it work, but I keep getting errors, (I am not very advanced, not sure what I am doing wrong). I entered this in index.html

{{ define "main" }}
{{ $url := "web.csv" }}
{{ $sep := "," }}

{{ /* $url */}}

{{ $tag := (index $r 14) }}
{{ range $i, $r := getCSV $sep $url }}
	{{ $tag = $tag | append (index $r 14) }}
{{ end }}
{{ $tag = uniq $tag | sort }}

<h2>Directory of Libraries in the United States</h2>
<ul>
{{ range $tag }}
	{{ $list := . }}
	<li>{{ . }}
	{{ range where $i, $r := getCSV $sep $url  (index $r 14) $list }}
		<ul>
			<li>{{ (index $r 14)}}
				<ul>
					
			</li>
		</ul>
	{{ end }}
	</li>
{{ end }}
</ul>

Server complains about $r

parse failed undefined variable “$r”

If you have any idea, where I have gone wrong, I’d be super thankful ^^

You are using $r in the same range definition where you define it, so it has no value, hence undefined.

Also, I suspect you have that whole line wrong syntax-wise. I don’t think you can use where like that with the assignment after it and … yea that whole line looks very wrong.

I suggest getting more familiar with how where 1 2 works, how range works, and you probably need another set of parenthesis around the getCSV call in that line.

It would be simpler if your data were in JSON, TOML, or YAML format, but if you’re stuck with CSV…

foo.csv

name,type
Felix,cat
Spot,dog
Rover,dog

template

{{/* Wrangle the CSV into a slice of objects. */}}
{{ $csv := getCSV "," "foo.csv" }}
{{ $cols := index $csv 0 }}
{{ $data := slice }}
{{ range $k, $v := $csv }}
  {{ if $k }}
    {{ $m := dict }}
    {{ range seq 0 (sub (len $cols) 1) }}
      {{ $m = merge $m (dict (index $cols .) (index $v .)) }}
    {{ end }}
    {{ $data = $data | append $m }}
  {{ end }}
{{ end }}

{{/* Build unique, sorted slice of types. */}}
{{ $types := slice }}
{{ range $data }}
  {{ $types = $types | append .type }}
{{ end }}
{{ $types = $types | uniq | sort }}

{{/* Display the grouped data. */}}
<ul>
  {{ range $types }}
    <li>
      {{ . }}
      <ul>
        {{ range where $data "type" . }}
          <li>{{ .name }}</li>
        {{ end }}
      </ul>
    </li>
  {{ end }}
</ul>

result

image

1 Like

Thanks! I’ll give this a try!

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