有谁知道在Go上漂亮地打印JSON输出的简单方法吗?
我正在寻找的用途都非常漂亮 - 打印出来的结果json.Marshal
并且只是格式化了来自任何地方的JSON字符串,因此为了调试目的而更容易阅读。
发布于 2018-03-28 09:18:15
通过漂亮的印刷,我认为你的意思是缩进,像这样
{
"data": 1234
}
而不是
{"data":1234}
最简单的方法是使用MarshalIndent
,它可以让你指定你想如何通过indent
参数缩进。因此,json.MarshalIndent(data, "", " ")
将会使用四个空格进行缩进。
发布于 2018-03-28 10:23:59
如果你有一个你想要变成JSON的对象,接受的答案是非常好的。这个问题还提到漂亮的打印任何JSON字符串,这就是我想要做的。我只是想从POST请求中明确记录一些JSON(特别是CSP违规报告)。
要使用MarshalIndent
,你必须把Unmarshal
它变成一个对象。如果你需要的话,就去做吧,但我没有。如果你只需要漂亮地打印一个字节数组,普通的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()))
}
https://stackoverflow.com/questions/-100007824
复制相似问题