Foudel Foudel -4 years ago 142
JSON Question

What is the difference between json.Marshal and json.MarshalIndent using 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.

Answer Source

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"
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download