Go to Page Content

How To Add Structured Data (JSON-LD) to Hugo

James Fawks

Prevent Hugo from adding backslashes to the URLs in your structured data.

The issue is Hugo is automatically escaping the JSON data when you encapsulate it in the script block. No combination of printf, safeHTML, or safeJS on the individual data will stop Hugo from reformating the data.

To prevent Hugo from reformating the data, you need to build the JSON structured data—make sure to format the data correctly—manually in a scratchpad. Then, use a printf statement to output the HTML directly to bypass Hugo.

{{- $jsonld := newScratch -}}
{{- $jsonld.Set "@type" "WebSite" -}}
{{- $jsonld.Set "@id" (printf "%s#website" site.BaseURL) -}}
{{- $jsonld.Set "url" site.BaseURL -}}
{{- $jsonld.Set "name" site.Title -}}
{{- $jsonld.Set "description" site.Home.Description -}}
{{- $jsonld.Set "inLanguage" "en-US" -}}
{{ printf `<script type="application/ld+json">%s</script>` ($jsonld | jsonify) | safeHTML }}

The above is a workaround until Hugo adds a directive that allows you to bypass the auto-formatting.

I hope this helps anyone that is running into this issue.

Happy Coding!

Related blogs

Rails Development with Docker Without Losing AutoReloading and AutoLoading

One of the most annoying things for me is working on a Rails project using Docker for development that is improperly configured, losing the automatic reloading of application constants and modules, forcing you to restart the Rails server each time you make a change.
Read in 6 minutes