data.GetJSON
Syntax
data.GetJSON INPUT... [OPTIONS]
Returns
any
Alias
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 := "" }}
{{ $p := "data/books.json" }}
{{ with resources.Get $p }}
{{ $opts := dict "delimiter" "," }}
{{ $data = . | transform.Unmarshal $opts }}
{{ else }}
{{ errorf "无法获取资源 %q" $p }}
{{ end }}
页面资源替代方案
考虑在访问页面资源时,使用 Resources.Get
方法与 transform.Unmarshal
结合使用。
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 "无法获取资源 %q" $p }}
{{ end }}
远程资源替代方案
考虑在访问远程资源以提高错误处理和缓存控制时,使用 resources.GetRemote
函数与 transform.Unmarshal
结合使用。
{{ $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 "无法获取远程资源 %q" $u }}
{{ end }}