我从端点检索 JSON 作为 GET 响应
response, _ := http.Get("https://website-returning-json-value.com")
data, _ := ioutil.ReadAll(response.Body)
w.Write(data)
它返回一个 JSON 值,这没问题,但非常难看(没有缩进等)。我想让它漂亮。我读过有像 MarshalIndent 这样的 util 函数可以完成这项工作,但这适用于 JSON 对象(?)并且 ReadAll 函数返回 []byte,所以它不起作用。我阅读了有关 encoding/json 包的文档,但信息很多,我有点困惑/困惑。
据我所知,我应该通过 ReadAll 函数获取 []byte -> 将其转换为 JSON -> 美化它 -> 再次转向 []byte。
最佳答案
有json.Indent()
以此目的。使用示例:
src := []byte(`{"foo":"bar","x":1}`)
dst := &bytes.Buffer{}
if err := json.Indent(dst, src, "", " "); err != nil {
panic(err)
}
fmt.Println(dst.String())
输出(在 Go Playground 上尝试):
{
"foo": "bar",
"x": 1
}
但缩进只是为了人眼,它携带相同的信息,图书馆不需要缩进 JSON。
另见:Is there a jq wrapper for golang that can produce human readable JSON output?
关于json - 从 GoLang 中的响应中检索到的漂亮 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52741013/