小编典典

是否有用于golang的jq包装器,它可以产生人类可读的JSON输出?

json

我正在编写一个go程序(我们称其为foo),该程序在Standard Out上输出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输出。


阅读 311

收藏
2020-07-27

共1个答案

小编典典

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这些indent功能的2个参数是:

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"
+-}
+}
2020-07-27