invopop / jsonschema

Generate JSON Schemas from Go types
MIT License
475 stars 83 forks source link

can you generate JSONschema from an enum? #145

Open straz opened 3 weeks ago

straz commented 3 weeks ago

My enum looks like this:

type ImageType string

const (
    JPG    ImageType = "jpg"
    GIF    ImageType = "gif"
    TIFF   ImageType = "tiff"
    PNG    ImageType = "png"
)

but when I run jsonschema.ReflectFromType all I get is this

{"$schema": "https://json-schema.org/draft/2020-12/schema", "type": "string"}

It doesn't even contain the name of the enum as the value of $ref. I assume that the output I need is something like this, am I right? If so, how do I generate this?

{
  "$schema": "http://json-schema.org/draft/2020-12/schema",
  "$ref": "#/$defs/ImageType",
  "$defs": {
    "ImageType": {
      "properties": {
        "type": "string",
        "enum": ["jpg", "gif", "tiff", "png"]
      }
    }
  }
}
straz commented 3 weeks ago

Additionally, if I create astruct like this with an enum field:

type Avatar struct {
    Name    string   `json:"name"`
    Type    ImageType   `json:"type"`
}

the output jsonschema ignores the type, and just uses string. How do I get it to restrict this to the enum values instead?

{
  "Avatar": {
    "properties": {
      "name": {
        "type": "string"
      },
      "type": {
        "type": "string"
      }
    }
  }
}