From da6de4ce90065927b0adc0db34145c8754c253cc Mon Sep 17 00:00:00 2001 From: Mathew Tonkin Henwood <7479946+mathewTH@users.noreply.github.com> Date: Thu, 5 Jan 2023 18:06:39 +1300 Subject: [PATCH 1/2] Add FieldNameTag config Allows field names to be based on a different tag. Json is still the default tag so this is not a breaking change. https://github.com/invopop/jsonschema/discussions/28#discussioncomment-4387240 --- reflect.go | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/reflect.go b/reflect.go index 6ebc6be..399c2ff 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{} @@ -989,7 +992,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) { From 7f2e6ffc7310bf17be38d1046538da52f8b5fb7d Mon Sep 17 00:00:00 2001 From: Balakrishnan Balasubramanian Date: Tue, 18 Apr 2023 16:55:37 -0400 Subject: [PATCH 2/2] Add test for FieldNameTag --- fixtures/test_config.json | 23 +++++++++++++++++++++++ reflect_test.go | 12 ++++++++++++ 2 files changed, 35 insertions(+) create mode 100644 fixtures/test_config.json 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_test.go b/reflect_test.go index c0d2c9f..566a965 100644 --- a/reflect_test.go +++ b/reflect_test.go @@ -545,3 +545,15 @@ func TestArrayFormat(t *testing.T) { pt := p.Items.Format require.Equal(t, pt, "uri") } + +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{}) +}