Home >Backend Development >Golang >How Can Go's `json.MarshalIndent` Function Help Pretty-Print JSON Data?
Pretty-Printing JSON in Go
When working with JSON output in Go, you may encounter situations where readability and formatting are crucial for easier comprehension. To address this need, Go provides the json.MarshalIndent function, which offers a simple and effective way to pretty-print JSON data.
Functionality of json.MarshalIndent
json.MarshalIndent takes three arguments:
By specifying the prefix and indent arguments, you can customize the formatting of your JSON output. For instance:
import ( "encoding/json" "fmt" ) func main() { data := map[string]int{"data": 1234} prettyPrintJSON, err := json.MarshalIndent(data, "", " ") if err != nil { fmt.Println(err) return } fmt.Println(string(prettyPrintJSON)) }
This code will output:
{ "data": 1234 }
where each line is indented with four spaces. The prefix argument has been left empty, resulting in no prefixes being added to the output.
Use Cases
json.MarshalIndent is particularly useful in the following scenarios:
The above is the detailed content of How Can Go's `json.MarshalIndent` Function Help Pretty-Print JSON Data?. For more information, please follow other related articles on the PHP Chinese website!