Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I detect unneeded fields in JSON when using Go?

When using Go to serialize json into a struct, I need to detect when there are fields present in the json which are not present in the struct. For example:

type Foo struct {
    Bar string `json:"bar"`
}
{
  "bar": 1,
  "baz": 2
}

By default, Go will just ignore the baz field and do nothing with it. How do I detect if extra fields are present and do something in that case?

I can probably unmarshal json into an interface{} instead of a pre-defined struct and then check what keys it has, but that would really complicate the logic of the rest of my app and add a lot of unnecessary validation code, so I'd prefer not to do that.

like image 460
flexagoon Avatar asked Oct 21 '25 11:10

flexagoon


1 Answers

You can do this with the json.Decoder DisallowUnknownFields method:

package main

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

type Foo struct {
    Bar string `json:"bar"`
}

func main() {
    input := []byte(`{
  "bar": "1",
  "baz": 2
}`)
    foo := Foo{}
    br := bytes.NewReader(input)
    decoder := json.NewDecoder(br)
    decoder.DisallowUnknownFields()
    err := decoder.Decode(&foo) // err = json: unknown field "baz"
    fmt.Printf("Result: %v\n", err)
}

Go Playground reference: https://go.dev/play/p/8TRYLnhNiz0

like image 152
BMitch Avatar answered Oct 23 '25 01:10

BMitch