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 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘