我正在编写一个go计划(让我们称之为foo),它在标准输出上输出JSON.
$ ./foo
{"id":"uuid1","name":"John Smith"}{"id":"uuid2","name":"Jane Smith"}
Run Code Online (Sandbox Code Playgroud)
为了使输出人类可读,我必须将其输入jq,如:
$ ./foo | jq .
{
"id":"uuid1",
"name": "John Smith"
}
{
"id":"uuid2"
"name": "Jane Smith"
}
Run Code Online (Sandbox Code Playgroud)
有没有办法使用开源的jq包装器来实现相同的结果?我尝试找到一些,但他们通常包含过滤JSON输入的功能,而不是美化JSON输出.
该encoding/json软件包支持开箱即用的漂亮输出.你可以用json.MarshalIndent().或者如果你正在使用json.Encoder,那么在调用之前调用它Encoder.SetIndent()(自Go以来的新方法)方法Encoder.Encode().
例子:
m := map[string]interface{}{"id": "uuid1", "name": "John Smith"}
data, err := json.MarshalIndent(m, "", " ")
if err != nil {
panic(err)
}
fmt.Println(string(data))
enc := json.NewEncoder(os.Stdout)
enc.SetIndent("", " ")
if err := enc.Encode(m); err != nil {
panic(err)
}
Run Code Online (Sandbox Code Playgroud)
输出(在Go Playground上试试):
{
"id": "uuid1",
"name": "John Smith"
}
{
"id": "uuid1",
"name": "John Smith"
}
Run Code Online (Sandbox Code Playgroud)
如果您只想格式化"就绪"JSON文本,可以使用以下json.Indent()函数:
src := `{"id":"uuid1","name":"John Smith"}`
dst := &bytes.Buffer{}
if err := json.Indent(dst, []byte(src), "", " "); err != nil {
panic(err)
}
fmt.Println(dst.String())
Run Code Online (Sandbox Code Playgroud)
输出(在Go Playground上试试):
{
"id": "uuid1",
"name": "John Smith"
}
Run Code Online (Sandbox Code Playgroud)
string这些indent功能的2个参数是:
prefix, indent string
Run Code Online (Sandbox Code Playgroud)
解释在文档中:
JSON对象或数组中的每个元素都以一个新的缩进行开始,该行以前缀开头,后跟根据缩进嵌套的一个或多个缩进副本.
因此,每个换行符将以启动时开始prefix,后面将跟随0或更多副本indent,具体取决于嵌套级别.
如果您为它们指定值,则变得清晰明显:
json.Indent(dst, []byte(src), "+", "-")
Run Code Online (Sandbox Code Playgroud)
使用嵌入对象测试它:
src := `{"id":"uuid1","name":"John Smith","embedded:":{"fieldx":"y"}}`
dst := &bytes.Buffer{}
if err := json.Indent(dst, []byte(src), "+", "-"); err != nil {
panic(err)
}
fmt.Println(dst.String())
Run Code Online (Sandbox Code Playgroud)
输出(在Go Playground上试试):
{
+-"id": "uuid1",
+-"name": "John Smith",
+-"embedded:": {
+--"fieldx": "y"
+-}
+}
Run Code Online (Sandbox Code Playgroud)