Senior
What is the difference between json.Unmarshal and json.Decoder, and when would you use each?
sobes.tech AI
Answer from AI
json.Unmarshal and json.Decoder are two ways to decode JSON in Go, but they have different use cases:
-
json.Unmarshaltakes the entire JSON as a byte slice ([]byte) and immediately tries to parse it into a specified structure. This is convenient when you have the whole JSON in memory. -
json.Decoderworks with a stream (e.g.,io.Reader), allowing you to read and decode JSON in parts. This is useful for large data or when JSON arrives over the network or from a file gradually.
When to use:
- If the JSON is small and available entirely —
json.Unmarshalis simpler and faster. - If the JSON is large, or you want to read multiple JSON objects from a single stream, or process data as it arrives — use
json.Decoder.
Example with json.Decoder for reading multiple JSON objects from a stream:
decoder := json.NewDecoder(reader)
for {
var obj MyStruct
if err := decoder.Decode(&obj); err == io.EOF {
break
} else if err != nil {
log.Fatal(err)
}
// process obj
}