data.GetJSON
语法
data.GetJSON INPUT... [OPTIONS]
返回值
any
别名
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": "Les Misérables"
},
{
"author": "Victor Hugo",
"rating": 4,
"title": "The Hunchback of Notre Dame"
}
]
选项
通过提供选项映射将标头添加到请求
{{ $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 "Unable to get resource %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 "Unable to get resource %q" $p }}
{{ end }}
远程资源替代方案
当访问远程资源时,请考虑使用 resources.GetRemote
函数和 transform.Unmarshal
,以改进错误处理和缓存控制。
{{ $data := dict }}
{{ $url := "https://example.org/books.json" }}
{{ with try (resources.GetRemote $url) }}
{{ with .Err }}
{{ errorf "%s" . }}
{{ else with .Value }}
{{ $data = . | transform.Unmarshal }}
{{ else }}
{{ errorf "Unable to get remote resource %q" $url }}
{{ end }}
{{ end }}