check if json has fields other than valid keys in struct

Use func (*Decoder) DisallowUnknownFields():

DisallowUnknownFields causes the Decoder to return an error when the destination is a struct and the input contains object keys which do not match any non-ignored, exported fields in the destination.

package main

import (
    "encoding/json"
    "fmt"
    "strings"
)

type Junk struct {
    ID   int    `json:"id"`
    Name string `json:"name"`
    Area string `json:"area"`
}

func main() {
    a := Junk{}
    data := `{"id":1,"name":"gg","junk":"Junk value"}`

    d := json.NewDecoder(strings.NewReader(data))
    d.DisallowUnknownFields()

    if err := d.Decode(&a); err != nil {
        fmt.Println(err)
    }
    fmt.Println(a)
}

Try it out: https://play.golang.org/p/aTj2C-AAuZ7

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top