diff --git a/fixtures/test_config.json b/fixtures/test_config.json new file mode 100644 index 0000000..97149b8 --- /dev/null +++ b/fixtures/test_config.json @@ -0,0 +1,23 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://github.com/invopop/jsonschema/config", + "$ref": "#/$defs/Config", + "$defs": { + "Config": { + "properties": { + "name": { + "type": "string" + }, + "count": { + "type": "integer" + } + }, + "additionalProperties": false, + "type": "object", + "required": [ + "name", + "count" + ] + } + } +} diff --git a/reflect.go b/reflect.go index fb5d12d..6eb3fc0 100644 --- a/reflect.go +++ b/reflect.go @@ -183,6 +183,9 @@ type Reflector struct { // root as opposed to a definition with a reference. ExpandedStruct bool + // FieldNameTag will change the tag used to get field names. json tags are used by default. + FieldNameTag string + // IgnoredTypes defines a slice of types that should be ignored in the schema, // switching to just allowing additional properties instead. IgnoredTypes []interface{} @@ -990,7 +993,11 @@ func ignoredByJSONSchemaTags(tags []string) bool { } func (r *Reflector) reflectFieldName(f reflect.StructField) (string, bool, bool, bool) { - jsonTagString, _ := f.Tag.Lookup("json") + tagKey := r.FieldNameTag + if tagKey == "" { + tagKey = "json" + } + jsonTagString := f.Tag.Get(tagKey) jsonTags := strings.Split(jsonTagString, ",") if ignoredByJSONTags(jsonTags) { diff --git a/reflect_test.go b/reflect_test.go index fe2a030..4908f4e 100644 --- a/reflect_test.go +++ b/reflect_test.go @@ -547,3 +547,15 @@ func TestArrayExtraTags(t *testing.T) { pt = p.Items.Pattern require.Equal(t, pt, "^https://.*") } + +func TestFieldNameTag(t *testing.T) { + type Config struct { + Name string `yaml:"name"` + Count int `yaml:"count"` + } + + r := Reflector{ + FieldNameTag: "yaml", + } + compareSchemaOutput(t, "fixtures/test_config.json", &r, &Config{}) +}