data.GetJSON
Instead, use transform.Unmarshal
with a global, page, or remote resource.
See the remote data example.
Given the following directory structure:
my-project/
βββ other-files/
βββ books.json
Access the data with either of the following:
{{ $data := getJSON "other-files/books.json" }}
{{ $data := getJSON "other-files/" "books.json" }}
When working with local data, the file path is relative to the working directory.
Access remote data with either of the following:
{{ $data := getJSON "https://example.org/books.json" }}
{{ $data := getJSON "https://example.org/" "books.json" }}
The resulting data structure is a JSON object:
[
{
"author": "Victor Hugo",
"rating": 5,
"title": "Les MisΓ©rables"
},
{
"author": "Victor Hugo",
"rating": 4,
"title": "The Hunchback of Notre Dame"
}
]
Optionsβ
Add headers to the request by providing an options map:
{{ $opts := dict "Authorization" "Bearer abcd" }}
{{ $data := getJSON "https://example.org/books.json" $opts }}
Add multiple headers using a slice:
{{ $opts := dict "X-List" (slice "a" "b" "c") }}
{{ $data := getJSON "https://example.org/books.json" $opts }}
Global resource alternativeβ
Consider using the resources.Get
function with transform.Unmarshal
when accessing a global resource.
my-project/
βββ assets/
βββ data/
βββ books.json
{{ $data := dict }}
{{ $p := "data/books.json" }}
{{ with resources.Get $p }}
{{ $data = . | transform.Unmarshal }}
{{ else }}
{{ errorf "Unable to get resource %q" $p }}
{{ end }}
Page resource alternativeβ
Consider using the Resources.Get
method with transform.Unmarshal
when accessing a page resource.
my-project/
βββ content/
βββ posts/
βββ reading-list/
βββ books.json
βββ index.md
{{ $data := dict }}
{{ $p := "books.json" }}
{{ with .Resources.Get $p }}
{{ $data = . | transform.Unmarshal }}
{{ else }}
{{ errorf "Unable to get resource %q" $p }}
{{ end }}
Remote resource alternativeβ
Consider using the resources.GetRemote
function with transform.Unmarshal
when accessing a remote resource to improve error handling and cache control.
{{ $data := dict }}
{{ $u := "https://example.org/books.json" }}
{{ with resources.GetRemote $u }}
{{ with .Err }}
{{ errorf "%s" . }}
{{ else }}
{{ $data = . | transform.Unmarshal }}
{{ end }}
{{ else }}
{{ errorf "Unable to get remote resource %q" $u }}
{{ end }}