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

How Can I Pretty-Print JSON Data in Go?

DDD
Release: 2024-12-21 00:31:14
Original
715 people have browsed it

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
// }
Copy after login

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!

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