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 (

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))

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

Try it out:

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top