Nested JSON array unmarshal - possible?

Is it possible to work with a nested JSON array using unmarshal ?

My (simplified) data looks like this:

[
  [
    {
      "foo":"foo",
      "bar":"foo"
     },
     {
      "foo":"foo2",
      "bar":"foo2"
     }
   ],
   [
    {
      "foo":"foo3",
      "bar":"foo3"
     }
    ]
]

I’m not quite clear how I do nested iteration in Hugo ?

Ideally I also need to keep track of where I am on the outer array, since the inner arrays are grouped by a key and so I need display items in the same group context (i.e. its not just a case of e.g. printing out all the foo). In practical terms I’m building a custom table, and so each group would be within one row (<tr></tr>).

It would be helpful if you provided an example, based on the data shown, of what the table should look like.

To generated a nested unordered list:

  {{ $data := "" }}
  {{ $path := "data.json" }}
  {{ with resources.Get $path }}
    {{ with unmarshal .Content }}
      {{ $data = . }}
    {{ end }}
  {{ else }}
    {{ errorf "Unable to get global resource %q" $path }}
  {{ end }}

  {{ with $data }}
    <ul>
      {{ range $k, $v := . }}
        <li>
          {{ $k }}
          {{ with $v }}
            <ul>
              {{ range  . }}
                <li>foo = {{ .foo }}</li>
                <li>bar = {{ .bar }}</li>
              {{ end }}
            </ul>
          {{ end }}
        </li>
      {{ end }}
    </ul>
  {{ end }}

Result:

image

Lacking example aside, I think you essentially answered the question that fortunately the Hugo unmarshal is not recursive and therefore I just nest the range or with tags …

{{ with unmarshal . }}
{{ $data = . }}
{{ end }}
{{ range $data }}
    {{ range . }}
    {{end}}
{{end}}

So thank you.

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