英文:
What is the difference between json.Marshal and json.MarshalIndent using Go?
问题
我想要以JSON格式输出CF命令的结果,但我不确定应该使用json.Marshal
还是json.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])
这里需要一个新的示例,使用json.MarshalIndent
}
我从未使用过Go语言,所以我真的不知道应该使用哪个函数以及如何使用。
英文:
I would like to get an output of a CF command in JSON format but I am not sure what to use either json.Marshal
or json.MarshalIndent
.
The output I need is like this:
{
"key1": "value1",
....
"keyn": "valuen",
}
This is the old example but it is not the desired output:
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
}
I never used go so I really do not know which one to use and how.
答案1
得分: 16
我认为文档对此非常清楚。json.Marshal()
和json.MarshalIndent()
都会生成一个 JSON 文本结果(以[]byte
形式),但前者会以紧凑的方式输出,没有缩进,而后者则应用了(可以自定义的)缩进。引用自json.MarshalIndent()
的文档:
> MarshalIndent 类似于 Marshal,但会应用 Indent 来格式化输出。
看下面这个简单的例子:
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"
}
英文:
I think the doc is pretty clear on this. Both json.Marshal()
and json.MarshalIndent()
produces a JSON text result (in the form of a []byte
), but while the former does a compact output without indentation, the latter applies (somewhat customizable) indent. Quoting from doc of json.MarshalIndent()
:
> MarshalIndent is like Marshal but applies Indent to format the output.
See this simple example:
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)
The output is (try it on the Go Playground):
{"key":"value"} <nil>
{
"key": "value"
} <nil>
There is also 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)
}
Output (try this one on the Go Playground):
{"key":"value"}
{
"key": "value"
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论