json.Unmarshal vs json.NewDecoder.Decode: which to choose for parsing JSON in Go?
Hi everyone! I just started learning Go and encountered a problem choosing between `json.Unmarshal` and `json.NewDecoder.Decode` for parsing JSON. Both methods do the same thing — decode JSON into a struct, but the documentation says there are nuances.
Here's an example I wrote:
```go
package main
import (
"encoding/json"
"fmt"
"strings"
)
type User struct {
Name string `json:"name"`
Age int `json:"age"`
}
func main() {
jsonStr := `{"name": "Alice", "age": 30}`
// Option 1
var user1 User
err := json.Unmarshal([]byte(jsonStr), &user1)
if err != nil {
fmt.Println("Unmarshal error:", err)
}
fmt.Println(user1)
// Option 2
var user2 User
decoder := json.NewDecoder(strings.NewReader(jsonS
No answers yet.
Log in to leave an answer