How to render JSON data in Hugo without creating corresponding markdown files for each JSON object

The goal is to create a listing page with links to individual detail pages for each item in a JSON file. The detail pages should also be included in the sitemap.xml file.
The expected URL format for each detail page should be: http://localhost:1313/custom/:id/,
where :id is the ID of the corresponding item in the JSON file.

It’s preferable to avoid creating corresponding markdown files in the content/ directory for each item in the JSON file. [more then 20k json objects]

So far, the listing page with links to detail pages works, but the detail pages return a 404 error.

Here’s an example of the JSON file located at data/test.json

[
   {
      "id":1,
      "title":"Custom Item 1",
      "description":"This is the description for Custom Item 1."
   },
   {
      "id":2,
      "title":"Custom Item 2",
      "description":"This is the description for Custom Item 2."
   },
   {
      "id":3,
      "title":"Custom Item 3",
      "description":"This is the description for Custom Item 3."
   }
]

Here are the relevant code snippets for the listing and detail pages:
layouts/custom/list.html

{{ range $key, $current := $data }}
     <h2><a href="{{ urlize "/custom/" }}{{ $current.id }}/">{{ $current.title }}</a></h2>
    <p>{{ $current.description }}</p>
{{ end }}

layouts/custom/single.html

{{- $data := getJSON "data/custom.json" -}}
{{- $current := index $data .Params.id -}}

<h2>{{ $current.title }}</h2>
<p>{{ $current.description }}</p>

I hope this helps clarify the approach!

1 Like

This is not yet possible to my understanding. There is an open ticket on GitHub, however completion depends on the developers: Build pages from data source #5074

But Hugo cannot, using a data set of items, build a page for each of them plus related list pages like it does from the content directory files.

For the time being, one solution would be to create a shell script to produce a markdown file for each entry. Not an elegant one, but should be easy using jq or any similar tool.

so only solution is to create markdown file and render content from json data source

You can generate pages from data using a couple of techniques, but this is probably the most flexible approach:

https://www.thenewdynamic.com/article/toward-using-a-headless-cms-with-hugo-part-2-building-from-remote-api/

Here’s a multilingual example:
https://github.com/jmooring/hugo-pages-from-data

1 Like

I have built a number of sites for clients that are generated from json retrieved via APIs.

For me the simplest is to use a script that creates markdown files from json. You can create the script in whatever language you are comfortable with, in my case that is Python.

You can see an example here: Build Hugo site with Notion and Airtable API – xdeb.org