我如何使用 Go 漂亮地打印 JSON?

新手上路,请多包涵

有谁知道在 Go 中漂亮打印 JSON 输出的简单方法?

我想漂亮地打印 json.Marshal 的结果,以及格式化现有的 JSON 字符串,以便于阅读。

原文由 Brad Peabody 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.8k
2 个回答

MarshalIndent 将允许您输出带有缩进和间距的 JSON。例如:

 {
    "data": 1234
}

indent 参数指定要缩进的字符系列。因此, json.MarshalIndent(data, "", " ") 将使用四个空格进行缩进。

原文由 Alexander Bauer 发布,翻译遵循 CC BY-SA 4.0 许可协议

如果您有一个想要转换为 JSON 的对象,那么接受的答案是很好的。这个问题还提到了漂亮地打印任何 JSON 字符串,这就是我想要做的。我只是想从 POST 请求(特别是 CSP 违规报告)中漂亮地记录一些 JSON。

要使用 MarshalIndent ,您必须将 Unmarshal 放入对象中。如果你需要那个,那就去吧,但我没有。如果你只需要漂亮地打印一个字节数组,plain Indent 是你的朋友。

这是我最终得到的:

 import (
    "bytes"
    "encoding/json"
    "log"
    "net/http"
)

func HandleCSPViolationRequest(w http.ResponseWriter, req *http.Request) {
    body := App.MustReadBody(req, w)
    if body == nil {
        return
    }

    var prettyJSON bytes.Buffer
    error := json.Indent(&prettyJSON, body, "", "\t")
    if error != nil {
        log.Println("JSON parse error: ", error)
        App.BadRequest(w)
        return
    }

    log.Println("CSP Violation:", string(prettyJSON.Bytes()))
}

原文由 robyoder 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题