json.Unmarshal vs json.NewDecoder.Decode: what's the difference in Go?
Hi everyone! I'm new to Go and trying to understand JSON parsing. I see that the standard library has two ways: `json.Unmarshal` and `json.NewDecoder().Decode()`. Both seem to do the same thing — convert JSON into a Go data structure. But I don't understand when to use which.
For example, I have this code:
```go
type User struct {
Name string `json:"name"`
Age int `json:"age"`
}
// Method 1
data := `{"name":"Alice","age":30}`
var user1 User
err := json.Unmarshal([]byte(data), &user1)
// Method 2
reader := strings.NewReader(data)
var user2 User
err = json.NewDecoder(reader).Decode(&user2)
```
Both options work the same way. But I've heard that `Decoder` is better for streams, and `Unmarshal` is for small data. What's the real difference? Is there a difference
No answers yet.
Log in to leave an answer
Blogs