-2

When parsing JSON with Go, is it possible to fail if a value is null or missing, without having to check every single field via an if statement? For example:

package main

import (
    "encoding/json"
    "fmt"
)

type Bird struct {
    Species     string `json:"birdType"`
    Description string `json:"what it does"`
}

func main() {
    birdJson := `{"birdType": "pigeon"}`
    var bird Bird
    json.Unmarshal([]byte(birdJson), &bird)
    fmt.Println(bird)
}

I'd expect to raise an error since "what it does" is not defined

mh-cbon
  • 6,683
  • 2
  • 27
  • 51
August
  • 1,600
  • 4
  • 18
  • 32
  • Go doesn't throw, you should instead check the error returned by `json.Unmarshal`. To the specifics of your question though, the feature you're looking for is not implemented by `encoding/json`. You can instead validate the struct's fields after you are done unmarshaling. And in case you need the reverse, i.e. return error if json contains unknown fields, that is actually [possible](https://pkg.go.dev/encoding/json@go1.17#Decoder.DisallowUnknownFields). – mkopriva Aug 26 '21 at 08:35
  • So I'd have to do that for every single field? – August Aug 26 '21 at 08:36
  • That is correct. – mkopriva Aug 26 '21 at 08:37
  • Are there any libraries, which could do that for me at all? This seems like quite a big feature missing :/. Also, could you add an answer so I can accept it? – August Aug 26 '21 at 08:38
  • There are libraries that do that, I don't use any of them so I can't recommend any, but if you search for "go validate" or "validation" or something like that you should get a bunch of suggestions in the results. Even here on SO, many people who use those libs often post questions about them. – mkopriva Aug 26 '21 at 08:40

1 Answers1

0

No, encoding/json.Unmarshal will not return an error if the target struct has fields for which the source json does not contain any matching object keys.

mkopriva
  • 28,154
  • 3
  • 45
  • 61