Skip to content

Commit

Permalink
Merge pull request #126 from abemedia/fix/inline-tag
Browse files Browse the repository at this point in the history
fix: support json inline tag
  • Loading branch information
samlown authored Feb 19, 2024
2 parents 9b6bb6e + 6da915f commit fc39d9b
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 0 deletions.
17 changes: 17 additions & 0 deletions fixtures/inlining_tag.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://github.com/invopop/jsonschema/outer-inlined",
"properties": {
"text": {
"type": "string"
},
"Foo": {
"type": "string"
}
},
"additionalProperties": false,
"type": "object",
"required": [
"Foo"
]
}
14 changes: 14 additions & 0 deletions reflect.go
Original file line number Diff line number Diff line change
Expand Up @@ -976,6 +976,15 @@ func ignoredByJSONSchemaTags(tags []string) bool {
return tags[0] == "-"
}

func inlinedByJSONTags(tags []string) bool {
for _, tag := range tags[1:] {
if tag == "inline" {
return true
}
}
return false
}

// toJSONNumber converts string to *json.Number.
// It'll aso return whether the number is valid.
func toJSONNumber(s string) (json.Number, bool) {
Expand Down Expand Up @@ -1037,6 +1046,11 @@ func (r *Reflector) reflectFieldName(f reflect.StructField) (string, bool, bool,
}
}

// As per JSON Marshal rules, inline nested structs that have `inline` tag.
if inlinedByJSONTags(jsonTags) {
return "", true, false, false
}

// Try to determine the name from the different combos
name := f.Name
if jsonTags[0] != "" {
Expand Down
6 changes: 6 additions & 0 deletions reflect_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,11 @@ type OuterNamed struct {
Inner `json:"inner"`
}

type OuterInlined struct {
Text `json:"text,omitempty"`
Inner `json:",inline"`
}

type OuterPtr struct {
*Inner
Text `json:",omitempty"`
Expand Down Expand Up @@ -419,6 +424,7 @@ func TestSchemaGeneration(t *testing.T) {
{&Outer{}, &Reflector{ExpandedStruct: true}, "fixtures/inlining_inheritance.json"},
{&OuterNamed{}, &Reflector{ExpandedStruct: true}, "fixtures/inlining_embedded.json"},
{&OuterNamed{}, &Reflector{ExpandedStruct: true, AssignAnchor: true}, "fixtures/inlining_embedded_anchored.json"},
{&OuterInlined{}, &Reflector{ExpandedStruct: true}, "fixtures/inlining_tag.json"},
{&OuterPtr{}, &Reflector{ExpandedStruct: true}, "fixtures/inlining_ptr.json"},
{&MinValue{}, &Reflector{}, "fixtures/schema_with_minimum.json"},
{&TestNullable{}, &Reflector{}, "fixtures/nullable.json"},
Expand Down

0 comments on commit fc39d9b

Please sign in to comment.