Skip to content

Commit d08b492

Browse files
committed
Fix faulty discriminator
1 parent fd0f15b commit d08b492

File tree

2 files changed

+49
-2
lines changed

2 files changed

+49
-2
lines changed

inferred_schema.go

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -136,14 +136,14 @@ func (i *InferredSchema) Infer(value any, hints Hints) *InferredSchema {
136136

137137
if discriminator, ok := hints.PeekActiveDiscriminator(); ok {
138138
if mappingKey, ok := m[discriminator].(string); ok {
139-
inferRest := NewInferredSchema().Infer(m, hints)
139+
delete(m, discriminator)
140140

141141
return &InferredSchema{
142142
SchemaType: SchemaTypeDiscriminator,
143143
Discriminator: Discriminator{
144144
Discriminator: discriminator,
145145
Mapping: map[string]*InferredSchema{
146-
mappingKey: inferRest,
146+
mappingKey: NewInferredSchema().Infer(m, hints),
147147
},
148148
},
149149
}
@@ -295,11 +295,15 @@ func (i *InferredSchema) Infer(value any, hints Hints) *InferredSchema {
295295
return &InferredSchema{SchemaType: SchemaTypeAny}
296296
}
297297

298+
delete(m, i.Discriminator.Discriminator)
299+
298300
if _, ok := i.Discriminator.Mapping[mappingKey]; !ok {
299301
i.Discriminator.Mapping[mappingKey] = NewInferredSchema()
300302
}
301303

302304
i.Discriminator.Mapping[mappingKey] = i.Discriminator.Mapping[mappingKey].Infer(m, hints)
305+
306+
return i
303307
}
304308

305309
if i.SchemaType == SchemaTypeDiscriminator {

inferrer_test.go

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,3 +72,46 @@ func TestJTDInferrerWithHints(t *testing.T) {
7272

7373
assert.EqualValues(t, expectedSchema, gotSchema)
7474
}
75+
76+
func TestJTDInferWithDiscriminatorHints(t *testing.T) {
77+
hints := Hints{
78+
Discriminator: HintSet{
79+
Values: [][]string{
80+
{"-", "type"},
81+
},
82+
},
83+
}
84+
85+
rows := []string{
86+
`[{"type": "s", "value": "foo"},{"type": "n", "value": 3.14}]`,
87+
}
88+
89+
inferrer := NewInferrer(hints)
90+
91+
for _, row := range rows {
92+
rowAsJSON := make([]any, 0)
93+
require.NoError(t, json.Unmarshal([]byte(row), &rowAsJSON))
94+
inferrer = inferrer.Infer(rowAsJSON)
95+
}
96+
97+
expectedSchema := Schema{
98+
Elements: &Schema{
99+
Discriminator: "type",
100+
Mapping: map[string]Schema{
101+
"s": {
102+
Properties: map[string]Schema{
103+
"value": {Type: jtd.TypeString},
104+
},
105+
},
106+
"n": {
107+
Properties: map[string]Schema{
108+
"value": {Type: jtd.TypeFloat64},
109+
},
110+
},
111+
},
112+
},
113+
}
114+
gotSchema := inferrer.IntoSchema()
115+
116+
assert.EqualValues(t, expectedSchema, gotSchema)
117+
}

0 commit comments

Comments
 (0)