从GoLang的响应中检索了漂亮的JSON [英] Pretty JSON retrieved from response in GoLang

查看:58
本文介绍了从GoLang的响应中检索了漂亮的JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从端点检索JSON作为GET响应

I retrieve JSON as GET response from and endpoint

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包的文档,但是有很多信息,但我有些卡住/困惑.

It returns me a JSON value, which is OK, but it is very ugly (no indents etc.). I would like to make it pretty. I've read that there is util function like MarshalIndent which does the job, but this works for JSON object (?) and ReadAll function returns []byte, so it does not work. I read the documentation regarding encoding/json package but there's a lot of information and I got a little bit stuck/confused.

据我了解,应该通过ReadAll函数获取[] byte->将其转换为JSON->美化它->再次转换为[] byte.

As far as I understand it should be done, I should get []byte via ReadAll function -> convert it to the JSON -> prettify it -> turn to []byte again.

推荐答案

json.Indent() .使用它的示例:

There is json.Indent() for this purpose. Example using it:

src := []byte(`{"foo":"bar","x":1}`)

dst := &bytes.Buffer{}
if err := json.Indent(dst, src, "", "  "); err != nil {
    panic(err)
}

fmt.Println(dst.String())

输出(在转到游乐场上尝试):

{
  "foo": "bar",
  "x": 1
}

但是缩进仅适用于人眼,它包含相同的信息,并且库不需要缩进的JSON.

But indentation is just for human eyes, it carries the same information, and libraries don't need indented JSON.

另请参阅: 查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆