Generate json from data files

What is the best way to loop through a folder full of data files and have hugo generate a single .json file from the combined data?

data

  • image-data
    • cat-photo.yml
    • dog-photo.yml
    • raccoon-photo.yml
    • yak-photo.yml

all-photos.json

1 Like

The best way would probably be to create an index.json template under your site’s layouts/ folder (create it if necessary). Include the necessary code to build the JSON inside that file. Then, in your site’s configuration file, add “JSON” to the output formats for home. An example from my own site, where I build a JSON search index:

In the JSON file:

[
  {{- $links := apply (where $.Site.Pages "Kind" "page") "partial" "search_item.json" "." -}}
  {{- $clean := apply $links "chomp" "." -}}
  {{ delimit $clean "," }}
]

In the configuration file:

[outputs]
    home = ["HTML", "CSS", "RSS", "JSON"]

The only limitation to this method is that you can only build one .json file this way. To build multiple for different purposes, you’d have to do something different.

1 Like

Hey, @jeremyzilar!

You can create a custom output type of JSON (e.g. home = ["HTML", "JSON"] ) in your config, and create a template, like index.json, with something like this:

{{- $.Scratch.Add "index" slice -}}
{{$content := .Site.Data.image-data}}
{{- range $content -}}
  {{- $.Scratch.Add "index" (dict "foo" .bar ) -}}
{{- end -}}
{{- $.Scratch.Get "index" | jsonify -}}
 

You can look around the forums for this little construct, because it's been used quite a bit. I have some examples, too.
1 Like

Posted at the same time as @Shadow53 - I’m sure that would work too, and they’re pretty similar.

1 Like