json.Unmarshal with disallowUnknownFields

905 views
Skip to first unread message

Brian Candler

unread,
Jul 30, 2020, 4:45:25 AM7/30/20
to golang-nuts
I want to do a json.Unmarshal of []byte data whilst also getting the disallowUnknownFields behaviour.  Is there any tidier way than this?

dec := json.NewDecoder(bytes.NewReader(data))
dec.DisallowUnknownFields()
var v mystruct
err := dec.Decode(&v)

roger peppe

unread,
Jul 30, 2020, 8:47:24 AM7/30/20
to Brian Candler, golang-nuts
You could write a function to do that for you.

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/5c1c7101-8ead-46b2-9e58-8b7f26203be0o%40googlegroups.com.

Brian Candler

unread,
Jul 30, 2020, 10:17:27 AM7/30/20
to golang-nuts
Sure, I now have this as a drop-in replacement for json.Unmarshal:

func StrictUnmarshal(data []byte, v interface{}) error {
dec := json.NewDecoder(bytes.NewReader(data))
dec.DisallowUnknownFields()
return dec.Decode(v)
}

I just wondered if I was missing something.
Reply all
Reply to author
Forward
0 new messages