Skip to content

Property description is not respected for typed strings #169

@Leguu

Description

@Leguu

If you have a typed string, descriptions defined in JSONSchema and JSONSchemaExtend are not respected (they're dropped). In my application, I have a typed string that has a common description throughout the app, but jsonschema drops that custom description (I don't want to duplicate the description tag across many instances of that string).

Reproducing example:

type Bar string

func (Bar) JSONSchemaExtend(s *jsonschema.Schema) {
	s.Title = "This is a Bar title"
	s.Description = "I have a description!"
}

type Foo struct {
	BarProperty Bar
}

func main() {
	json, _ := jsonschema.Reflect(Foo{}).MarshalJSON()
	fmt.Println(string(json))
}

Current (invalid) output:

{"$schema":"https://json-schema.org/draft/2020-12/schema","$ref":"#/$defs/Foo","$defs":{"Foo":{"properties":{"BarProperty":{"type":"string","title":"This is a Bar title"}},"additionalProperties":false,"type":"object","required":["BarProperty"]}}}

Expected output:

{"$schema":"https://json-schema.org/draft/2020-12/schema","$ref":"#/$defs/Foo","$defs":{"Foo":{"properties":{"BarProperty":{"type":"string","title":"This is a Bar title","description":"I have a description!"}},"additionalProperties":false,"type":"object","required":["BarProperty"]}}}

Cause

I believe the issue is here, reflectStructFields calls structKeywordsFromTags which overwrites the description.

property.structKeywordsFromTags(f, st, name)

t.Description = f.Tag.Get("jsonschema_description")

Suggested fix

Struct property tags in general should overwrite the base schema, but we should check that the jsonschema_description tag is present before overwriting the description.

Change:

func (t *Schema) structKeywordsFromTags(f reflect.StructField, parent *Schema, propertyName string) {
	t.Description = f.Tag.Get("jsonschema_description")

	tags := splitOnUnescapedCommas(f.Tag.Get("jsonschema"))
        ...

To:

func (t *Schema) structKeywordsFromTags(f reflect.StructField, parent *Schema, propertyName string) {
	description, exists := f.Tag.Lookup("jsonschema_description")
	if exists {
		t.Description = description
	}

	tags := splitOnUnescapedCommas(f.Tag.Get("jsonschema"))
        ...

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions