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

Susan Sarandon
Release: 2024-11-20 11:31:55
Original
710 people have browsed it

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))
Copy after login

Output:

{
  "id": "uuid1",
  "name": "John Smith"
}
Copy after login
Copy after login

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())
Copy after login

Output:

{
  "id": "uuid1",
  "name": "John Smith"
}
Copy after login
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template