The json.Indent function in Golang is part of the encoding/json package and is used to format JSON-encoded data with indentation. This function is particularly useful when you need to make JSON data more readable by adding line breaks and indentations, making it easier to inspect or debug.
Table of Contents
- Introduction
json.IndentFunction Syntax- Examples
- Basic Usage
- Customizing Indentation
- Indenting JSON from a String
- Real-World Use Case Example
- Conclusion
Introduction
The json.Indent function allows you to take a compact JSON-encoded byte slice and format it with indentation and newlines. This is especially helpful when you want to output JSON in a human-readable format, such as when logging or displaying JSON data in a user interface.
json.Indent Function Syntax
The syntax for the json.Indent function is as follows:
func Indent(dst *bytes.Buffer, src []byte, prefix, indent string) error
Parameters:
dst: A pointer to abytes.Bufferwhere the indented JSON data will be written.src: A byte slice containing the original, compact JSON-encoded data.prefix: A string to be added at the beginning of each line (optional).indent: A string that defines the indentation to be used for each level of the JSON hierarchy.
Returns:
error: An error value that is non-nil if the input JSON data is invalid or cannot be indented.
Examples
Basic Usage
This example demonstrates how to use json.Indent to add indentation to a compact JSON string.
Example
package main
import (
"bytes"
"encoding/json"
"fmt"
)
func main() {
src := []byte(`{"Name":"John Doe","Email":"john.doe@example.com","Age":30}`)
var dst bytes.Buffer
err := json.Indent(&dst, src, "", " ")
if err != nil {
fmt.Println("Error indenting JSON:", err)
return
}
fmt.Println(dst.String())
}
Output:
{
"Name": "John Doe",
"Email": "john.doe@example.com",
"Age": 30
}
Explanation:
- The
json.Indentfunction is used to format the JSON data with two spaces of indentation, making it more readable.
Customizing Indentation
This example shows how to customize the prefix and indentation characters in the JSON output.
Example
package main
import (
"bytes"
"encoding/json"
"fmt"
)
func main() {
src := []byte(`{"Name":"John Doe","Email":"john.doe@example.com","Age":30}`)
var dst bytes.Buffer
err := json.Indent(&dst, src, "> ", "\t")
if err != nil {
fmt.Println("Error indenting JSON:", err)
return
}
fmt.Println(dst.String())
}
Output:
> {
> "Name": "John Doe",
> "Email": "john.doe@example.com",
> "Age": 30
> }
Explanation:
- The JSON data is indented using a tab character, and each line is prefixed with
"> ", making the output customized to specific formatting needs.
Indenting JSON from a String
This example demonstrates how to indent JSON data read from a string and output it in a human-readable format.
Example
package main
import (
"bytes"
"encoding/json"
"fmt"
)
func main() {
jsonStr := `{"Name":"John Doe","Email":"john.doe@example.com","Age":30}`
var dst bytes.Buffer
err := json.Indent(&dst, []byte(jsonStr), "", " ")
if err != nil {
fmt.Println("Error indenting JSON:", err)
return
}
fmt.Println("Indented JSON:", dst.String())
}
Output:
Indented JSON: {
"Name": "John Doe",
"Email": "john.doe@example.com",
"Age": 30
}
Explanation:
- The JSON string is indented with four spaces per level, making it more readable and suitable for display or debugging purposes.
Real-World Use Case Example: Formatting JSON for Logs
A practical use case for json.Indent is formatting JSON data for logging purposes, where readability is essential.
Example: Indenting JSON for Logs
package main
import (
"bytes"
"encoding/json"
"fmt"
"log"
)
type LogEntry struct {
Timestamp string `json:"timestamp"`
Level string `json:"level"`
Message string `json:"message"`
}
func main() {
entry := LogEntry{
Timestamp: "2024-08-10T12:34:56Z",
Level: "INFO",
Message: "Application started successfully",
}
var src bytes.Buffer
encoder := json.NewEncoder(&src)
err := encoder.Encode(entry)
if err != nil {
fmt.Println("Error encoding JSON:", err)
return
}
var dst bytes.Buffer
err = json.Indent(&dst, src.Bytes(), "", " ")
if err != nil {
fmt.Println("Error indenting JSON:", err)
return
}
log.Println("Formatted Log Entry:\n", dst.String())
}
Explanation:
- The
json.Indentfunction is used to format a JSON-encoded log entry, making it more readable when written to log files or displayed in the console.
Conclusion
The json.Indent function in Go is used for formatting JSON data in a human-readable way. It is especially useful when you need to inspect, debug, or log JSON data, providing a clear and structured view of the JSON content. Whether you are working with API responses, configuration files, or log entries, json.Indent offers a simple and effective way to enhance the readability of your JSON data.