是否有一个golang的jq包装器可以生成人类可读的JSON输出?

问题描述 投票:4回答:1

我正在编写一个go计划(让我们称之为foo),它在标准输出上输出JSON。

$ ./foo
{"id":"uuid1","name":"John Smith"}{"id":"uuid2","name":"Jane Smith"}

为了使输出人类可读,我必须将其输入jq,如:

$ ./foo | jq .

{
"id":"uuid1",
"name": "John Smith"
}
{
"id":"uuid2"
"name": "Jane Smith"
}

有没有办法使用开源的jq包装器来实现相同的结果?我尝试找到一些,但他们通常包含过滤JSON输入的功能,而不是美化JSON输出。

json go jq
1个回答
7
投票

encoding/json包支持开箱即用的漂亮输出。你可以使用json.MarshalIndent()。或者,如果你正在使用json.Encoder,那么在调用Encoder.SetIndent()之前调用它的Go 1.7(自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)
}

输出(在Go Playground上试试):

{
  "id": "uuid1",
  "name": "John Smith"
}
{
  "id": "uuid1",
  "name": "John Smith"
}

如果您只想格式化“就绪”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())

输出(在Go Playground上试试):

{
  "id": "uuid1",
  "name": "John Smith"
}

这些string函数的2个indent参数是:

prefix, indent string

解释在文档中:

JSON对象或数组中的每个元素都以一个新的缩进行开始,该行以前缀开头,后跟根据缩进嵌套的一个或多个缩进副本。

因此每个换行符将以prefix开头,后面会有0个或更多个indent副本,具体取决于嵌套级别。

如果您为它们指定值,则变得清晰明显:

json.Indent(dst, []byte(src), "+", "-")

使用嵌入对象测试它:

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())

输出(在Go Playground上试试):

{
+-"id": "uuid1",
+-"name": "John Smith",
+-"embedded:": {
+--"fieldx": "y"
+-}
+}
© www.soinside.com 2019 - 2024. All rights reserved.