Skip to content

Instantly share code, notes, and snippets.

@GithubUser5462
Created November 25, 2023 18:20
Show Gist options
  • Save GithubUser5462/3a5ffff89f0f79d8dd289e79b1ffc086 to your computer and use it in GitHub Desktop.
Save GithubUser5462/3a5ffff89f0f79d8dd289e79b1ffc086 to your computer and use it in GitHub Desktop.
Golang: Generate an error when a JSON field is present but the corresponding struct field is missing - Disallow Unknown Fields
package main
import (
"bytes"
"encoding/json"
"fmt"
)
type User struct {
Name string `json:"name"`
Age int `json:"age"`
}
func main() {
jsonString := `{"name": "John Doe", "age": 30, "location": "New York"}`
var user User
dec := json.NewDecoder(bytes.NewReader([]byte(jsonString)))
dec.DisallowUnknownFields()
err := dec.Decode(&user)
if err != nil {
fmt.Println("err:", "Decode:", err)
}
fmt.Printf("%+v\n", user)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment