0
0
GoHow-ToBeginner · 2 min read

Go How to Convert Struct to JSON with Example

Use the json.Marshal() function from the encoding/json package to convert a struct to JSON in Go, like jsonData, err := json.Marshal(yourStruct).
📋

Examples

Input{"Name":"Alice","Age":30}
Output{"Name":"Alice","Age":30}
Input{"Name":"Bob","Age":0}
Output{"Name":"Bob","Age":0}
Input{"Name":"","Age":25}
Output{"Name":"","Age":25}
🧠

How to Think About It

To convert a struct to JSON in Go, you first import the encoding/json package. Then you use the json.Marshal() function, which takes your struct and returns the JSON bytes and an error. You handle the error and convert the bytes to a string to see the JSON output.
📐

Algorithm

1
Import the encoding/json package.
2
Create and fill your struct with data.
3
Call json.Marshal() with your struct as argument.
4
Check if there is an error returned.
5
If no error, convert the returned bytes to string.
6
Print or use the JSON string as needed.
💻

Code

go
package main

import (
	"encoding/json"
	"fmt"
)

type Person struct {
	Name string
	Age  int
}

func main() {
	p := Person{Name: "Alice", Age: 30}
	jsonData, err := json.Marshal(p)
	if err != nil {
		fmt.Println("Error:", err)
		return
	}
	fmt.Println(string(jsonData))
}
Output
{"Name":"Alice","Age":30}
🔍

Dry Run

Let's trace converting a Person struct with Name 'Alice' and Age 30 to JSON.

1

Create struct

p = Person{Name: "Alice", Age: 30}

2

Call json.Marshal

jsonData, err = json.Marshal(p) // jsonData = []byte('{"Name":"Alice","Age":30}')

3

Convert bytes to string

string(jsonData) = '{"Name":"Alice","Age":30}'

StepActionValue
1Create structPerson{Name: "Alice", Age: 30}
2Marshal structjsonData = []byte('{"Name":"Alice","Age":30}')
3Convert to string'{"Name":"Alice","Age":30}'
💡

Why This Works

Step 1: Use encoding/json package

The encoding/json package provides the Marshal function to convert Go data structures to JSON format.

Step 2: Marshal converts struct to bytes

json.Marshal() takes the struct and returns JSON as a byte slice, which is a raw data format.

Step 3: Convert bytes to string

To print or use the JSON, convert the byte slice to a string with string(jsonData).

🔄

Alternative Approaches

Use json.MarshalIndent for pretty JSON
go
package main

import (
	"encoding/json"
	"fmt"
)

type Person struct {
	Name string
	Age  int
}

func main() {
	p := Person{Name: "Alice", Age: 30}
	jsonData, err := json.MarshalIndent(p, "", "  ")
	if err != nil {
		fmt.Println("Error:", err)
		return
	}
	fmt.Println(string(jsonData))
}
This formats JSON with indentation for readability but uses more space.
Use json.NewEncoder to write JSON directly to output
go
package main

import (
	"encoding/json"
	"os"
)

type Person struct {
	Name string
	Age  int
}

func main() {
	p := Person{Name: "Alice", Age: 30}
	encoder := json.NewEncoder(os.Stdout)
	encoder.Encode(p)
}
This writes JSON directly to a writer like stdout, useful for streaming or files.

Complexity: O(n) time, O(n) space

Time Complexity

The time depends on the size of the struct fields and their values, as json.Marshal processes each field once.

Space Complexity

The output JSON bytes require extra memory proportional to the struct size, so space is O(n).

Which Approach is Fastest?

Using json.Marshal is fast and simple; json.MarshalIndent adds overhead for formatting; json.NewEncoder is efficient for streaming.

ApproachTimeSpaceBest For
json.MarshalO(n)O(n)Simple JSON conversion
json.MarshalIndentO(n)O(n)Readable, pretty JSON
json.NewEncoderO(n)O(n)Streaming JSON output
💡
Always check the error returned by json.Marshal to avoid silent failures.
⚠️
Forgetting to handle the error returned by json.Marshal can cause unexpected crashes.