goccy / go-json

Fast JSON encoder/decoder compatible with encoding/json for Go
MIT License
3.12k stars 148 forks source link

Json fileds type validation #511

Open egor-ponomarev opened 6 months ago

egor-ponomarev commented 6 months ago

Hello all !

I would like to know if there is any way or any plan to have the ability of validation values/types of json fields when parsing? Let's say we have a struct with time.Time field:

type Country struct {
    Id        int
    CreatedAt time.Time
}

and try to parse a json where CreatedAt is an integer:

func TestWrongFieldType(t *testing.T) {
    // Arrange
    actualCity := &Country{}
    bytes := []byte("{\"id\":5, \"createdAt\": 2}")

    // Act
    // json = "github.com/goccy/go-json"
    err := json.Unmarshal(bytes, actualCity)

    // Assert
    assert.NotNil(t, err)
    assert.Equal(t, "Time.UnmarshalJSON: input is not a JSON string", err.Error())
}

Would it be possible to get in the error more detailed info, something like:

errors: [
   { 
       "createdAt": "wrong value"
   }
]

In case of several nested fields (including array fields) and several errors it could be:

errors: [
   { 
       "continent.name": "wrong value (or more detailed error description)"
   },
   { 
       "population.city[4].count": "wrong value (or more detailed error description)"
   },   
]

Thank you in advance!