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!