Marshal vs Unmarshal in Go: Key Differences and Usage
Marshal converts Go data structures into JSON bytes, turning your data into a format for storage or transfer. Unmarshal does the opposite: it reads JSON bytes and fills Go data structures with that data.Quick Comparison
This table summarizes the main differences between Marshal and Unmarshal in Go.
| Aspect | Marshal | Unmarshal |
|---|---|---|
| Purpose | Convert Go data to JSON bytes | Convert JSON bytes to Go data |
| Direction | Go struct → JSON | JSON → Go struct |
| Function Signature | func Marshal(v interface{}) ([]byte, error) | func Unmarshal(data []byte, v interface{}) error |
| Common Use Case | Prepare data for sending or saving | Read data received or loaded |
| Error Handling | Fails if Go data can't be encoded | Fails if JSON is invalid or mismatched |
| Output Type | Returns JSON byte slice | Modifies Go variable via pointer |
Key Differences
Marshal is used when you want to take your Go data, like structs or maps, and turn it into JSON format. This is useful when you want to send data over the internet or save it in a file. It returns a slice of bytes that represent the JSON.
Unmarshal works the other way around. It takes JSON data in bytes and fills your Go variables with the information. You must pass a pointer to the variable you want to fill, so Go knows where to put the data.
Errors can happen in both: Marshal can fail if your data contains types that can't be converted to JSON, while Unmarshal can fail if the JSON is not valid or doesn't match the Go data structure you provide.
Marshal Code Example
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 marshaling:", err) return } fmt.Println(string(jsonData)) }
Unmarshal Equivalent
package main import ( "encoding/json" "fmt" ) type Person struct { Name string Age int } func main() { jsonData := []byte(`{"Name":"Alice","Age":30}`) var p Person err := json.Unmarshal(jsonData, &p) if err != nil { fmt.Println("Error unmarshaling:", err) return } fmt.Printf("Name: %s, Age: %d\n", p.Name, p.Age) }
When to Use Which
Choose Marshal when you need to convert your Go data into JSON format for sending over a network, saving to a file, or logging. Use Unmarshal when you receive JSON data from an external source like an API or file and want to convert it into Go data structures to work with it in your program.
In short, Marshal is for encoding Go data to JSON, and Unmarshal is for decoding JSON back into Go data.
Key Takeaways
Marshal converts Go data into JSON bytes for output or storage.Unmarshal reads JSON bytes and fills Go variables with that data.Unmarshal so it can modify your variable.Marshal to send or save data, and Unmarshal to receive or load data.