json.Marshal 和 json.MarshalIndent 使用 Go 有什么区别?

What is the difference between json.Marshal and json.MarshalIndent using Go?

我想获得 JSON 格式的 CF 命令输出,但我不确定要使用什么 json.Marshaljson.MarshalIndent

我需要的输出是这样的:

{
    "key1": "value1",
     ....
    "keyn": "valuen",
}

这是旧示例,但不是所需的输出:

cmd.ui.Say(terminal.EntityNameColor(T("User-Provided:")))   
  for _, key := range keys {        
         // cmd.ui.Say("%s: %v", key, envVars[key])
         here needed a new one with json.marshalIdent
 }

我从来没有用过go,所以我真的不知道该用哪个以及怎么用。

我认为文档对此非常清楚。两者 json.Marshal()json.MarshalIndent() 产生 JSON 文本结果(以 []byte 的形式),但是前者没有缩进的紧凑输出,后者应用(有点可定制的)缩进。引用自 json.MarshalIndent() 的文档:

MarshalIndent is like Marshal but applies Indent to format the output.

看这个简单的例子:

type Entry struct {
    Key string `json:"key"`
}

e := Entry{Key: "value"}
res, err := json.Marshal(e)
fmt.Println(string(res), err)

res, err = json.MarshalIndent(e, "", "  ")
fmt.Println(string(res), err)

输出是(在 Go Playground 上尝试):

{"key":"value"} <nil>
{
  "key": "value"
} <nil>

还有json.Encoder:

type Entry struct {
    Key string `json:"key"`
}
e := Entry{Key: "value"}

enc := json.NewEncoder(os.Stdout)
if err := enc.Encode(e); err != nil {
    panic(err)
}

enc.SetIndent("", "  ")
if err := enc.Encode(e); err != nil {
    panic(err)
}

输出(在 Go Playground 上试试这个):

{"key":"value"}
{
  "key": "value"
}