encoding icon indicating copy to clipboard operation
encoding copied to clipboard

decoding of 'missing' json values goes totally undetected

Open qknight opened this issue 2 years ago • 0 comments

problem

in the example below there is an array of Example structs for which the second contains no values {}. The decoder does not complain and constrcuts the missing values with the default values for the respective types.

for me this goes against intuition of the programmer: a missing field should result in a decoder error, as: Field "event" was expected but not given.

func TestDecoderUndefinedJsonKeys(t *testing.T) {
	eventJSON := `[{"event":"foobar", "id": 55}, {}]`

	type Example struct {
		Event string `json:"event"`
		ID    uint64 `json:"id"`
	}

	var events []Example

	reader := strings.NewReader(eventJSON)
	decoder := json.NewDecoder(reader)
	decoder.UseNumber()
	decErr := decoder.Decode(&events)
	if decErr != nil {
		assert.NoError(t, decErr)
		return
	}
	assert.Equal(t, int(events[0].ID), 55)
	assert.Equal(t, events[0].Event, "foobar")

	// this confuses me
	assert.Equal(t, int(events[1].ID), 0)
	assert.Equal(t, events[1].Event, "")
}

this will execute as:

TestDecoderUndefinedJsonKeys
=== RUN   TestDecoderUndefinedJsonKeys
--- PASS: TestDecoderUndefinedJsonKeys (0.00s)
PASS

This test will run without an issue.

The setting: decoder.DisallowUnknownFields() would point out that unknown fields would result in an error. But as far as I can tell there is no such thing for 'expected' fields which were not set.

solution

i've checked the implementation and your issue tracker but this hasn't been discussed so far - to my surprise.

validator

a automated detected would require a validator as mentioned:

"github.com/alecthomas/jsonschema"
"github.com/xeipuuv/gojsonschema"

https://stackoverflow.com/questions/19633763/unmarshaling-json-in-go-required-field

manual checks

if the fields were pointers, one could manually check for nil. this is illustrated also in:

https://stackoverflow.com/questions/19633763/unmarshaling-json-in-go-required-field

go playground validator

https://github.com/go-playground/validator

strict decoding (wish)

i'd love if we had a

decoder.StrictDecoding() 

or

decoder.DisallowUnsetFields()

option which would enforce all struct values to be in the json and otherwise fail with an error.

thoughts

i'm interested on your thoughts on the matter.

qknight avatar Apr 28 '23 13:04 qknight