Skip to content

Commit 93b5a32

Browse files
lsdchrobtme
andauthored
fix: support json inline tag for embedding anonymous fields in schema (#1006)
Co-authored-by: Robert Thomas <[email protected]>
1 parent 34b2d39 commit 93b5a32

2 files changed

Lines changed: 52 additions & 1 deletion

File tree

‎schema.go‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -714,7 +714,13 @@ func getFields(typ reflect.Type, visited map[reflect.Type]struct{}) []fieldInfo
714714
continue
715715
}
716716

717-
if f.Anonymous && f.Tag.Get("json") == "" {
717+
// An anonymous (embedded) field is merged into the parent object when
718+
// it has no explicit JSON name. This covers both an absent tag and a
719+
// name-less tag such as `json:",inline"` or `json:",omitempty"`. Giving
720+
// the field a name (e.g. `json:"meta"`) makes it a nested object
721+
// instead, matching encoding/json's behavior.
722+
jsonName, _, _ := strings.Cut(f.Tag.Get("json"), ",")
723+
if f.Anonymous && jsonName == "" {
718724
embedded = append(embedded, f)
719725
continue
720726
}

‎schema_test.go‎

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -819,6 +819,51 @@ func TestSchema(t *testing.T) {
819819
}
820820
}`,
821821
},
822+
{
823+
name: "field-embed-inline",
824+
input: struct {
825+
Embedded `json:",inline"`
826+
Value2 string `json:"value2"`
827+
}{},
828+
expected: `{
829+
"type": "object",
830+
"additionalProperties": false,
831+
"required": ["value2", "value"],
832+
"properties": {
833+
"value": {
834+
"type": "string",
835+
"description": "new doc"
836+
},
837+
"value2": {
838+
"type": "string"
839+
}
840+
}
841+
}`,
842+
},
843+
{
844+
// A *named* (non-anonymous) field is never inlined by the standard
845+
// encoding/json marshaler that huma uses by default; the `,inline`
846+
// option is ignored and the field is nested under its Go name. The
847+
// schema must match that wire behavior.
848+
name: "field-named-inline",
849+
input: struct {
850+
Field Embedded `json:",inline"`
851+
Value2 string `json:"value2"`
852+
}{},
853+
expected: `{
854+
"type": "object",
855+
"additionalProperties": false,
856+
"required": ["Field", "value2"],
857+
"properties": {
858+
"Field": {
859+
"$ref": "#/components/schemas/Embedded"
860+
},
861+
"value2": {
862+
"type": "string"
863+
}
864+
}
865+
}`,
866+
},
822867
{
823868
name: "field-embed-mixed",
824869
input: struct {

0 commit comments

Comments
 (0)