Pretty-Printing JSON in Go

3 min read .

JSON (JavaScript Object Notation) is a popular format for data interchange. While JSON is typically compact and easy to parse, it can sometimes be difficult to read when it is all on one line. Pretty-printing JSON makes it more readable by formatting it with indents and line breaks. In Go, you can use the encoding/json package to achieve this. In this post, we’ll explore how to pretty-print JSON in Go, including working with both basic and more complex JSON structures.

1. Using json.MarshalIndent

Go’s standard library provides the json.MarshalIndent function, which allows you to marshal a Go data structure into JSON with indentation for readability. This is the simplest and most common method for pretty-printing JSON in Go.

Example:

package main

import (
	"encoding/json"
	"fmt"
)

func main() {
	// Define a sample data structure
	data := map[string]interface{}{
		"name": "Alice",
		"age":  30,
		"address": map[string]string{
			"street": "123 Main St",
			"city":   "Wonderland",
		},
		"hobbies": []string{"reading", "hiking", "coding"},
	}

	// Pretty-print JSON with indentation
	prettyJSON, err := json.MarshalIndent(data, "", "    ")
	if err != nil {
		fmt.Println("Error marshalling JSON:", err)
		return
	}

	fmt.Println(string(prettyJSON))
}

In this example, json.MarshalIndent is used to convert the data map into a JSON-formatted string with indentation. The second argument to MarshalIndent specifies the prefix for each line (in this case, an empty string), and the third argument specifies the indentation string (four spaces).

2. Handling Errors Gracefully

When working with JSON, it’s important to handle errors gracefully. The json.MarshalIndent function returns an error if the data structure cannot be marshaled to JSON. Proper error handling ensures that your application can manage unexpected situations.

Example:

package main

import (
	"encoding/json"
	"fmt"
)

func main() {
	// Define a sample data structure
	data := map[string]interface{}{
		"name": "Bob",
		"age":  25,
	}

	// Pretty-print JSON with indentation
	prettyJSON, err := json.MarshalIndent(data, "", "    ")
	if err != nil {
		fmt.Println("Error marshalling JSON:", err)
		return
	}

	fmt.Println("Pretty-Printed JSON:\n", string(prettyJSON))
}

In this example, we handle the error returned by json.MarshalIndent and provide a user-friendly error message if something goes wrong.

3. Pretty-Printing JSON from a File

If you need to pretty-print JSON that is read from a file, you can use Go’s os package to read the file and then use json.MarshalIndent to format the JSON.

Example:

package main

import (
	"encoding/json"
	"fmt"
	"log"
	"os"
)

func main() {
	// Read JSON from a file
	fileContent, err := os.ReadFile("data.json")
	if err != nil {
		log.Fatalf("Error reading file: %v", err)
	}

	// Unmarshal the JSON data
	var data interface{}
	if err := json.Unmarshal(fileContent, &data); err != nil {
		log.Fatalf("Error unmarshalling JSON: %v", err)
	}

	// Pretty-print JSON with indentation
	prettyJSON, err := json.MarshalIndent(data, "", "    ")
	if err != nil {
		log.Fatalf("Error marshalling JSON: %v", err)
	}

	fmt.Println("Pretty-Printed JSON:\n", string(prettyJSON))
}

In this example, os.ReadFile reads the JSON file into a byte slice. The JSON is then unmarshaled into an interface{} to handle arbitrary JSON structures. Finally, json.MarshalIndent is used to pretty-print the JSON.

4. Formatting JSON for API Responses

When building APIs, you might want to pretty-print JSON responses to make them more readable for debugging purposes. The following example demonstrates how to return a pretty-printed JSON response in an HTTP server.

Example:

package main

import (
	"encoding/json"
	"fmt"
	"net/http"
)

func handler(w http.ResponseWriter, r *http.Request) {
	data := map[string]interface{}{
		"status": "success",
		"data": map[string]string{
			"message": "Hello, World!",
		},
	}

	// Pretty-print JSON with indentation
	prettyJSON, err := json.MarshalIndent(data, "", "    ")
	if err != nil {
		http.Error(w, "Error marshalling JSON", http.StatusInternalServerError)
		return
	}

	w.Header().Set("Content-Type", "application/json")
	w.Write(prettyJSON)
}

func main() {
	http.HandleFunc("/", handler)
	fmt.Println("Server is running on http://localhost:8080")
	http.ListenAndServe(":8080", nil)
}

In this example, the HTTP handler function returns a pretty-printed JSON response using json.MarshalIndent. This makes the API response easier to read and debug.

Conclusion

Pretty-printing JSON in Go is a straightforward task using the json.MarshalIndent function from the encoding/json package. Whether you’re working with basic data structures, reading JSON from files, or formatting API responses, Go provides powerful tools for making JSON more readable. By incorporating pretty-printing into your Go applications, you can improve the readability of JSON data and make your code easier to work with.

Tags:
Golang

See Also

chevron-up