Home >Backend Development >Golang >How Can I Pretty-Print JSON Data in Go?

How Can I Pretty-Print JSON Data in Go?

DDD
DDDOriginal
2024-12-21 00:31:14759browse

How Can I Pretty-Print JSON Data in Go?

Pretty-printing JSON in Go

Formatting JSON to make it easier to read can be a challenge, but Go offers a convenient solution with json.MarshalIndent. This function allows you to prettify the output of json.Marshal or format an existing JSON string.

Using json.MarshalIndent

To prettify JSON using json.MarshalIndent, pass your data, the prefix (empty string for none), and the indent characters as arguments:

data := map[string]int{"data": 1234}
prettyJSON, err := json.MarshalIndent(data, "", "    ")
if err != nil {
    // Error handling
}

// Output:
// {
//     "data": 1234
// }

The indent argument specifies the indentation characters. For instance, json.MarshalIndent(data, "", " ") will pretty-print the JSON with four spaces for indentation.

The above is the detailed content of How Can I Pretty-Print JSON Data 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