Skip to content

Commit 1ec8c24

Browse files
authored
fix: jsonschema integer validation (#852)
1 parent a5fb553 commit 1ec8c24

File tree

2 files changed

+42
-10
lines changed

2 files changed

+42
-10
lines changed

jsonschema/validate.go

+4
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,10 @@ func Validate(schema Definition, data any) bool {
3636
_, ok := data.(bool)
3737
return ok
3838
case Integer:
39+
// Golang unmarshals all numbers as float64, so we need to check if the float64 is an integer
40+
if num, ok := data.(float64); ok {
41+
return num == float64(int64(num))
42+
}
3943
_, ok := data.(int)
4044
return ok
4145
case Null:

jsonschema/validate_test.go

+38-10
Original file line numberDiff line numberDiff line change
@@ -86,14 +86,6 @@ func TestUnmarshal(t *testing.T) {
8686
content []byte
8787
v any
8888
}
89-
var result1 struct {
90-
String string `json:"string"`
91-
Number float64 `json:"number"`
92-
}
93-
var result2 struct {
94-
String string `json:"string"`
95-
Number float64 `json:"number"`
96-
}
9789
tests := []struct {
9890
name string
9991
args args
@@ -108,7 +100,10 @@ func TestUnmarshal(t *testing.T) {
108100
},
109101
},
110102
content: []byte(`{"string":"abc","number":123.4}`),
111-
v: &result1,
103+
v: &struct {
104+
String string `json:"string"`
105+
Number float64 `json:"number"`
106+
}{},
112107
}, false},
113108
{"", args{
114109
schema: jsonschema.Definition{
@@ -120,7 +115,40 @@ func TestUnmarshal(t *testing.T) {
120115
Required: []string{"string", "number"},
121116
},
122117
content: []byte(`{"string":"abc"}`),
123-
v: result2,
118+
v: struct {
119+
String string `json:"string"`
120+
Number float64 `json:"number"`
121+
}{},
122+
}, true},
123+
{"validate integer", args{
124+
schema: jsonschema.Definition{
125+
Type: jsonschema.Object,
126+
Properties: map[string]jsonschema.Definition{
127+
"string": {Type: jsonschema.String},
128+
"integer": {Type: jsonschema.Integer},
129+
},
130+
Required: []string{"string", "integer"},
131+
},
132+
content: []byte(`{"string":"abc","integer":123}`),
133+
v: &struct {
134+
String string `json:"string"`
135+
Integer int `json:"integer"`
136+
}{},
137+
}, false},
138+
{"validate integer failed", args{
139+
schema: jsonschema.Definition{
140+
Type: jsonschema.Object,
141+
Properties: map[string]jsonschema.Definition{
142+
"string": {Type: jsonschema.String},
143+
"integer": {Type: jsonschema.Integer},
144+
},
145+
Required: []string{"string", "integer"},
146+
},
147+
content: []byte(`{"string":"abc","integer":123.4}`),
148+
v: &struct {
149+
String string `json:"string"`
150+
Integer int `json:"integer"`
151+
}{},
124152
}, true},
125153
}
126154
for _, tt := range tests {

0 commit comments

Comments
 (0)