Go How to Convert Struct to JSON with Example
json.Marshal() function from the encoding/json package to convert a struct to JSON in Go, like jsonData, err := json.Marshal(yourStruct).Examples
How to Think About It
Algorithm
Code
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)) }
Dry Run
Let's trace converting a Person struct with Name 'Alice' and Age 30 to JSON.
Create struct
p = Person{Name: "Alice", Age: 30}
Call json.Marshal
jsonData, err = json.Marshal(p) // jsonData = []byte('{"Name":"Alice","Age":30}')
Convert bytes to string
string(jsonData) = '{"Name":"Alice","Age":30}'
| Step | Action | Value |
|---|---|---|
| 1 | Create struct | Person{Name: "Alice", Age: 30} |
| 2 | Marshal struct | jsonData = []byte('{"Name":"Alice","Age":30}') |
| 3 | Convert 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
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)) }
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) }
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.
| Approach | Time | Space | Best For |
|---|---|---|---|
| json.Marshal | O(n) | O(n) | Simple JSON conversion |
| json.MarshalIndent | O(n) | O(n) | Readable, pretty JSON |
| json.NewEncoder | O(n) | O(n) | Streaming JSON output |