Home >Backend Development >Golang >How to Pretty Print JSON Output in Go Using Built-in Functions?

How to Pretty Print JSON Output in Go Using Built-in Functions?

Linda Hamilton
Linda HamiltonOriginal
2024-11-22 04:54:11653browse

How to Pretty Print JSON Output in Go Using Built-in Functions?

Pretty Printing JSON Output in Go with Built-in Functions

When dealing with JSON output in Go programs, it's often desirable to make it human readable. While jq can be used for this purpose, there are also built-in functions within the Go standard library that can achieve the desired result.

Json Marshal Indenting

The encoding/json package provides the json.MarshalIndent() function for pretty printing JSON output. It takes two additional parameters:

  • prefix: The string to add before each line
  • indent: The string to add after each level of indentation

By passing an empty string as the prefix and a space as the indent, you can obtain human readable JSON output:

m := map[string]interface{}{"id": "uuid1", "name": "John Smith"}

data, err := json.MarshalIndent(m, "", "  ")
if err != nil {
    panic(err)
}
fmt.Println(string(data))

Output:

{
  "id": "uuid1",
  "name": "John Smith"
}
{
  "id": "uuid1",
  "name": "John Smith"
}

You can also use the json.Encoder.SetIndent() method to set the indentation parameters when using an Encoder:

enc := json.NewEncoder(os.Stdout)
enc.SetIndent("", "  ")
if err := enc.Encode(m); err != nil {
    panic(err)
}

Json Indenting

If you already have a JSON string, you can use the json.Indent() function to format it:

src := `{"id":"uuid1","name":"John Smith"}`

dst := &bytes.Buffer{}
if err := json.Indent(dst, []byte(src), "", "  "); err != nil {
    panic(err)
}
fmt.Println(dst.String())

Output:

{
  "id": "uuid1",
  "name": "John Smith"
}

The above is the detailed content of How to Pretty Print JSON Output in Go Using Built-in Functions?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn