data.GetJSON

以下是目錄結構範例:

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

可以透過以下任一方式存取資料:

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

可以透過以下任一方式存取遠端資料:

{{ $data := getJSON "https://example.org/books.json" }}
{{ $data := getJSON "https://example.org/" "books.json" }}

結果的資料結構是一個 JSON 物件:

[
  {
    "author": "Victor Hugo",
    "rating": 5,
    "title": "悲慘世界"
  },
  {
    "author": "Victor Hugo",
    "rating": 4,
    "title": "鐘樓怪人"
  }
]

選項

透過提供選項映射來添加請求標頭:

{{ $opts := dict "Authorization" "Bearer abcd" }}
{{ $data := getJSON "https://example.org/books.json" $opts }}

使用切片來添加多個標頭:

{{ $opts := dict "X-List" (slice "a" "b" "c") }}
{{ $data := getJSON "https://example.org/books.json" $opts }}

全域資源替代方式

存取全域資源時,建議使用 resources.Get 函數搭配 transform.Unmarshal

my-project/
└── assets/
    └── data/
        └── books.json
{{ $data := dict }}
{{ $p := "data/books.json" }}
{{ with resources.Get $p }}
  {{ $data = . | transform.Unmarshal }}
{{ else }}
  {{ errorf "無法取得資源 %q" $p }}
{{ end }}

頁面資源替代方式

存取頁面資源時,建議使用 Resources.Get 方法搭配 transform.Unmarshal

my-project/
└── content/
    └── posts/
        └── reading-list/
            ├── books.json
            └── index.md
{{ $data := dict }}
{{ $p := "books.json" }}
{{ with .Resources.Get $p }}
  {{ $data = . | transform.Unmarshal }}
{{ else }}
  {{ errorf "無法取得資源 %q" $p }}
{{ end }}

遠端資源替代方式

存取遠端資源時,建議使用 resources.GetRemote 函數搭配 transform.Unmarshal,以改善錯誤處理與快取控制。

{{ $data := dict }}
{{ $u := "https://example.org/books.json" }}
{{ with resources.GetRemote $u }}
  {{ with .Err }}
    {{ errorf "%s" . }}
  {{ else }}
    {{ $data = . | transform.Unmarshal }}
  {{ end }}
{{ else }}
  {{ errorf "無法取得遠端資源 %q" $u }}
{{ end }}