Generate a json containing all pages with content

Apart from a standard sitemap I want hugo to generate a separate JSON-file in the following format:

[
    {
        "title": "First page",
        "content": "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua."
    },
    {
        "title": "Second page",
        "content": "At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet."
    }
]

containing all pages with title and content from my site.

I have no problem creating such a template and looping throug .Data.Pages with range – but where would I place and configure it?

_defaults/index.json - then enable the content type json for homepage.

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

You might have to define the json filetype, not sure.

You got me curious about this, so I played around. Here’s what I did:

(1) Configure output formats in config.toml:

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

(2) Add a JSON template at layouts/index.json.json, with contents:

{{ $pages := slice }}
{{ range .Pages }}
  {{ $pages = $pages | append (dict "title" .Title "content" .Plain) }}
{{ end }}
{{ $pages | jsonify }}

(3) Build your site and the JSON file will be generated at public/index.json

2 Likes