Golang json.MarshalIndent Function

The json.MarshalIndent function in Golang is part of the encoding/json package and is used to convert Go data structures into a formatted JSON string with indentation. This function is particularly useful when you need to output human-readable JSON, such as in logs, configuration files, or API responses intended for debugging purposes.

Table of Contents

  1. Introduction
  2. json.MarshalIndent Function Syntax
  3. Examples
    • Basic Usage
    • Customizing Indentation
    • Nested Structures with Indentation
  4. Real-World Use Case Example
  5. Conclusion

Introduction

The json.MarshalIndent function is similar to json.Marshal but adds the ability to format the resulting JSON string with indentation. This makes it easier to read and understand the structure of the JSON, which is particularly helpful during development and debugging. It also provides control over the prefix and indentation characters, allowing for customized output formatting.

json.MarshalIndent Function Syntax

The syntax for the json.MarshalIndent function is as follows:

func MarshalIndent(v interface{}, prefix, indent string) ([]byte, error)

Parameters:

  • v: The Go value (data structure) you want to convert to JSON. This can be of any type, including structs, slices, maps, and basic types.
  • prefix: A string to be added at the beginning of each line in the JSON output.
  • indent: A string that defines the indentation to be applied to each level of the JSON hierarchy.

Returns:

  • []byte: A byte slice containing the indented JSON encoding of the input data structure.
  • error: An error value that is non-nil if the data structure cannot be serialized into JSON.

Examples

Basic Usage

This example demonstrates how to use json.MarshalIndent to convert a Go struct into an indented JSON string.

Example

package main

import (
	"encoding/json"
	"fmt"
)

type User struct {
	Name  string
	Email string
	Age   int
}

func main() {
	user := User{Name: "John Doe", Email: "john.doe@example.com", Age: 30}
	jsonData, err := json.MarshalIndent(user, "", "  ")
	if err != nil {
		fmt.Println("Error marshaling JSON:", err)
		return
	}

	fmt.Println(string(jsonData))
}

Output:

{
  "Name": "John Doe",
  "Email": "john.doe@example.com",
  "Age": 30
}

Explanation:

  • The json.MarshalIndent function converts the User struct into a formatted JSON string with two spaces as indentation.

Customizing Indentation

This example shows how to customize the prefix and indentation characters in the JSON output.

Example

package main

import (
	"encoding/json"
	"fmt"
)

type User struct {
	Name  string
	Email string
	Age   int
}

func main() {
	user := User{Name: "John Doe", Email: "john.doe@example.com", Age: 30}
	jsonData, err := json.MarshalIndent(user, "> ", "    ")
	if err != nil {
		fmt.Println("Error marshaling JSON:", err)
		return
	}

	fmt.Println(string(jsonData))
}

Output:

> {
>     "Name": "John Doe",
>     "Email": "john.doe@example.com",
>     "Age": 30
> }

Explanation:

  • The json.MarshalIndent function is used with a custom prefix ("> ") and indentation (" " with four spaces).
  • The output JSON is formatted with the custom settings.

Nested Structures with Indentation

This example demonstrates how to serialize nested Go structs into an indented JSON string.

Example

package main

import (
	"encoding/json"
	"fmt"
)

type Address struct {
	Street string `json:"street"`
	City   string `json:"city"`
}

type User struct {
	Name    string  `json:"name"`
	Email   string  `json:"email"`
	Address Address `json:"address"`
}

func main() {
	user := User{
		Name:  "John Doe",
		Email: "john.doe@example.com",
		Address: Address{
			Street: "123 Main St",
			City:   "New York",
		},
	}
	jsonData, err := json.MarshalIndent(user, "", "  ")
	if err != nil {
		fmt.Println("Error marshaling JSON:", err)
		return
	}

	fmt.Println(string(jsonData))
}

Output:

{
  "name": "John Doe",
  "email": "john.doe@example.com",
  "address": {
    "street": "123 Main St",
    "city": "New York"
  }
}

Explanation:

  • The json.MarshalIndent function handles nested structs, formatting the JSON output with two spaces of indentation.

Real-World Use Case Example: Formatted JSON Output for Logging

A practical use case for json.MarshalIndent is creating readable JSON output for logging purposes.

Example: Logging Formatted JSON Data

package main

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

type ApiResponse struct {
	Status  string `json:"status"`
	Message string `json:"message"`
	Data    interface{} `json:"data"`
}

func main() {
	response := ApiResponse{
		Status:  "success",
		Message: "Data fetched successfully",
		Data: map[string]interface{}{
			"id":    1,
			"name":  "John Doe",
			"email": "john.doe@example.com",
		},
	}

	jsonData, err := json.MarshalIndent(response, "", "  ")
	if err != nil {
		log.Println("Error marshaling JSON:", err)
		return
	}

	log.Println("API Response:\n", string(jsonData))
}

Output:

API Response:
{
  "status": "success",
  "message": "Data fetched successfully",
  "data": {
    "id": 1,
    "name": "John Doe",
    "email": "john.doe@example.com"
  }
}

Explanation:

  • The json.MarshalIndent function formats the ApiResponse struct into an indented JSON string for easier readability in logs.
  • The formatted JSON string is then logged using the log.Println function.

Conclusion

The json.MarshalIndent function in Go provides a convenient way to generate human-readable JSON output. By allowing customization of the prefix and indentation, it makes the JSON data easier to read and understand, which is especially valuable for debugging, logging, and configuration management. Whether you are working with simple structures or complex nested data, json.MarshalIndent is used for producing well-formatted JSON in your applications.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top