Read local json file and output it in a ld+json script block

I wrote my own template quite a while ago and stayed on an old hugo version for quite some time and want to port everything to the newest version of hugo now. I used the following code within a partial template to read a local json file with schema.org markup and output it in a ld+json script block:

{{- if or (in .Params.ot_schema_org "Person") }}
<script type="application/ld+json">
	{{- getJSON "data/schema-org-Person.json" -}}
</script> 
{{ end -}}

I noticed that getJSON is now depricated. I tried to port this using the Unmarshal/Marshal/Remarshal function, however when I do so I always end up with an script Block where my json is enclosed in "s and escaped and therefore the schema can’t be read. I get

<script type=application/ld+json>"{\"@context\":\"https://schema.org/\ .... }"</script>

instead of the expected

<script type=application/ld+json>{"@context":"https://schema.org .... }</script>

I think this is for security reasons, but I have a really hard time to get it working. Can someone please explain how I can get this working again? My last try was:

{{- if or (in .Params.ot_schema_org "Person") }}
{{ with resources.Get "data/schema-org-Person.json" }}
<script type="application/ld+json">{{- transform.Remarshal "json" . -}}</script>
{{ end }}
{{ end -}}

Best regards
Tobias

Your JSON file is already JSON, so there’s no need to unmarshal or remarshal anything. Just render its content and indicate that it’s safe JS so that Go’s html/template package doesn’t escape the content.

{{ with resources.Get "data/schema-org-Person.json" }}
  <script type="application/ld+json">{{ .Content | safeJS }}</script>
{{ end }}

https://gohugo.io/methods/resource/content/
https://gohugo.io/functions/safe/js/

If for some reason you don’t trust the JSON in the data file, use this construct as described in the safe.JS documentation:

{{ with resources.Get "data/schema-org-Person.json" | unmarshal }}
  <script type="application/ld+json">{{ . }}</script>
{{ end }}
2 Likes

No getjson with a data file schema.json in the data folder. Have a look here:

Or here (on french):