How to generate a categories.json file?

Hi,

I am new to hugo, and I find it very cool “out of the box”, but quite difficult when you try to achieve something more.

I would like to generate a categories.json with hugo, listing all the categories from my website, but I could not find resources specifically dealing with this.

How can I achieve this ? bonus point if I can sort it by number of pages with every category :slight_smile:

Thanks you

You are looking for “custom output formats”, which is documented at:

Search the forums for examples of using custom output formats. :sunglasses:

In your config.toml file add something like this:

[outputs]
  taxonomy = ["HTML", "JSON"]

The outputs definition is per Page Kind ( page , home , section , taxonomy , or taxonomyTerm ): all taxonomies will have a JSON output… Not only categories

If you want JSON only for categories, add this to the category index file Front Matter (category/_index.md):

---
title: Categorie
outputs:
- html
- json
---

See here:

2 Likes

Hi,

I could not find what I was looking for: it seems so simple, yet nobody provides a handy guide to achieve this (or I could not find it).

I didn’t understand the Custom output format documentation, I find it non-intelligible (I got the theory though). Adding JSON to the outputs is not enough, you have to provide templates for that (of course), but it is fuzzy of what template to write and where to put it to see it applied. This is very confusing for a beginner IMHO.

Create the JSON template in layouts (or layouts/_default/ or layouts/taxonomy/). The file itself will be something like XXX.json

More here for templates organization & naming convention:

Here is a working solution, with json files for all taxonomies being created:

config.json

,
"outputs": {
    "taxonomyTerm": ["html", "json"]
}

layouts/_default/terms.json

{{- $.Scratch.Add "index" slice -}}
{{- range $index, $element := .Data.Pages.ByTitle -}}
    {{- $.Scratch.Add "index" (dict "id" $index "name" $element.Name "link" $element.Permalink) -}}
{{- end -}}
{{- $.Scratch.Get "index" | jsonify -}}

The big confusion for me at least is that taxonomyTerm is the list of the terms in the taxonomy and the taxonomy is a term in the taxonomy.

using Hugo Static Site Generator v0.70.0

1 Like