What is the difference between json.Marshal and json.MarshalIndent using Go?
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"
}
Foudel
Updated on June 05, 2022Comments
-
Foudel almost 2 years
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
orjson.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.