duanbicheng3345 2018-10-10 13:08
浏览 57
已采纳

从GoLang的响应中检索了漂亮的JSON

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)

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.

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.

  • 写回答

1条回答 默认 最新

  • drsw9390405 2018-10-10 13:15
    关注

    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())
    

    Output (try it on the Go Playground):

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

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

    Also see: Is there a jq wrapper for golang that can produce human readable JSON output?

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?