Home > Backend Development > Golang > How to Make JSON Output Human-Readable in Go?

How to Make JSON Output Human-Readable in Go?

DDD
Release: 2024-11-20 18:14:15
Original
672 people have browsed it

How to Make JSON Output Human-Readable in Go?

How to Generate Human Readable JSON Output in Go Using encoding/json

When outputting JSON in a Go program (known as "foo"), it may be beneficial to make the results human-readable for better interpretability. While it's common to use the jq command-line tool for this purpose by piping the output, this article presents an alternative solution using Go's built-in encoding/json package.

The encoding/json package provides native support for generating indented JSON without the need for external tools. By utilizing the json.MarshalIndent() function or calling json.Encoder.SetIndent() (available since Go 1.7), you can achieve the desired result.

For instance, to indent a map into readable 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

Alternatively, you can use json.Encoder with SetIndent():

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

You can also format existing JSON strings using json.Indent():

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

The prefix and indent parameters in these functions determine the indentation style. Prefix precedes each new line, while indent is repeated for each level of nesting.

By leveraging these methods, you can easily produce human-readable JSON in Go without the need for additional tools or dependencies, enhancing the readability and usability of your JSON output.

The above is the detailed content of How to Make JSON Output Human-Readable 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template