Home >Backend Development >Golang >How Can I Generate Human-Readable JSON Output in Go?

How Can I Generate Human-Readable JSON Output in Go?

Susan Sarandon
Susan SarandonOriginal
2024-11-20 11:31:55791browse

How Can I Generate Human-Readable JSON Output in Go?

Human-Readable JSON Output in Go

In Go, it's possible to generate human-readable JSON output without the need for an external jq wrapper. The encoding/json package provides built-in functions for prettifying JSON output.

Using json.MarshalIndent() or json.Encoder.SetIndent()

The json.MarshalIndent() function formats a Go value as a JSON string and indents it according to the specified prefix and indent characters.

For example, to format a map as JSON:

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"
}

You can also use the json.Encoder.SetIndent() method to indent the output from an encoder.

Using json.Indent()

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

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"
}

Customizing Indentation

The indent characters can be customized based on your preference. By default, the prefix is an empty string, and the indent is a single space. You can override these defaults to create a JSON output with the desired indentation style.

The above is the detailed content of How Can I Generate Human-Readable JSON Output in Go?. 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