hugo/docs/content/en/functions/data/GetJSON.md
Bjørn Erik Pedersen 5fd1e74903
Merge commit '9b0050e9aabe4be65c78ccf292a348f309d50ccd' as 'docs'
```
git subtree add --prefix=docs/ https://github.com/gohugoio/hugoDocs.git master --squash
```

Closes #11925
2024-01-27 10:48:57 +01:00

3.2 KiB

title description categories keywords action toc
data.GetJSON Returns a JSON object from a local or remote JSON file, or an error if the file does not exist.
aliases related returnType signatures
getJSON
functions/data/GetCSV
functions/resources/Get
functions/resources/GetRemote
methods/page/Resources
any
data.GetJSON INPUT... [OPTIONS]
true

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" }}

{{% note %}} When working with local data, the filepath is relative to the working directory. {{% /note %}}

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 := "" }}
{{ $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 := "" }}
{{ $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 := "" }}
{{ $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 }}