【问题标题】:How do i beautify the output in json?如何美化json中的输出?
【发布时间】:2020-07-13 19:28:48
【问题描述】:

所以我编写了这个非常简单的 Go 应用程序,它在 JSON 中显示了一堆信息,但所有输出数据都被缩小了,我需要一些帮助来美化所有数据。

func ExampleHandler(w http.ResponseWriter, r *http.Request) {
    w.Header().Add("Content-Type", "application/json")
    resp, _ := json.Marshal(map[string]string{
        "accept":                    r.Header.Get("Accept"),
    })
    w.Write(resp)
}

【问题讨论】:

    标签: arrays json go code-formatting


    【解决方案1】:

    使用json.Indent:

    resp, _ := json.Marshal(...)
    dst := bytes.Buffer{}
    json.Indent(&dst,resp,"","  ")
    w.Write(dsr.Bytes())
    

    【讨论】:

    • 嘿,我是新手,能不能帮帮我。
    • 答案中有什么不清楚的地方?查看json.Indent 的文档,或描述您的需求。
    【解决方案2】:

    改变

    resp, _ := json.Marshal(map[string]string{...})

    resp, _ := json.MarshalIndent(map[string]string{...}, "", " ")

    json.MarshalIndent()

    【讨论】:

    • A+ 谢谢你
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-07-27
    • 1970-01-01
    • 2011-10-29
    • 1970-01-01
    • 1970-01-01
    • 2012-02-24
    • 1970-01-01
    相关资源
    最近更新 更多