hugo/docs/content/en/functions/data/GetJSON.md
2023-10-20 09:43:56 +02:00

2.6 KiB

title linkTitle description categories keywords menu function relatedFunctions toc
data.GetJSON getJSON Returns a JSON object from a local or remote JSON file, or an error if the file does not exist.
functions
docs
parent
functions
aliases returnType signatures
getJSON
any
data.GetJSON PATHPART...
data.GetCSV
data.GetJSON
true

Given the following directory structure:

my-project/
└── other-files/
    └── books.json

Access the data with either of the following:

{{ $data := getCSV "," "other-files/books.json" }}
{{ $data := getCSV "," "other-files/" "books.json" }}

Access remote data with either of the following:

{{ $data := getCSV "," "https://example.org/books.json" }}
{{ $data := getCSV "," "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"
  }
]

Global resource alternative

Consider using resources.Get with transform.Unmarshal when accessing a global resource.

my-project/
└── assets/
    └── data/
        └── books.json
{{ $data := "" }}
{{ $p := "data/books.json" }}
{{ with resources.Get $p }}
  {{ $opts := dict "delimiter" "," }}
  {{ $data = . | transform.Unmarshal $opts }}
{{ else }}
  {{ errorf "Unable to get resource %q" $p }}
{{ end }}

Page resource alternative

Consider using .Resources.Get 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 }}
  {{ $opts := dict "delimiter" "," }}
  {{ $data = . | transform.Unmarshal $opts }}
{{ else }}
  {{ errorf "Unable to get resource %q" $p }}
{{ end }}

Remote resource alternative

Consider using resources.GetRemote with transform.Unmarshal for improved error handling when accessing a remote resource.

{{ $data := "" }}
{{ $u := "https://example.org/books.json" }}
{{ with resources.GetRemote $u }}
  {{ with .Err }}
    {{ errorf "%s" . }}
  {{ else }}
    {{ $opts := dict "delimiter" "," }}
    {{ $data = . | transform.Unmarshal $opts }}
  {{ end }}
{{ else }}
  {{ errorf "Unable to get remote resource %q" $u }}
{{ end }}