| 1 | // Copyright 2025 The JSON Schema Go Project Authors. All rights reserved. |
| 2 | // Use of this source code is governed by an MIT-style |
| 3 | // license that can be found in the LICENSE file. |
| 4 | |
| 5 | // This file contains functions that infer a schema from a Go type. |
| 6 | |
| 7 | package jsonschema |
| 8 | |
| 9 | import ( |
| 10 | "fmt" |
| 11 | "log/slog" |
| 12 | "maps" |
| 13 | "math/big" |
| 14 | "reflect" |
| 15 | "regexp" |
| 16 | "time" |
| 17 | ) |
| 18 | |
| 19 | // ForOptions are options for the [For] and [ForType] functions. |
| 20 | type ForOptions struct { |
| 21 | // If IgnoreInvalidTypes is true, fields that can't be represented as a JSON |
| 22 | // Schema are ignored instead of causing an error. |
| 23 | // This allows callers to adjust the resulting schema using custom knowledge. |
| 24 | // For example, an interface type where all the possible implementations are |
| 25 | // known can be described with "oneof". |
| 26 | IgnoreInvalidTypes bool |
| 27 | |
| 28 | // TypeSchemas maps types to their schemas. |
| 29 | // If [For] encounters a type that is a key in this map, the |
| 30 | // corresponding value is used as the resulting schema (after cloning to |
| 31 | // ensure uniqueness). |
| 32 | // Types in this map override the default translations, as described |
| 33 | // in [For]'s documentation. |
| 34 | TypeSchemas map[reflect.Type]*Schema |
| 35 | } |
| 36 | |
| 37 | // For constructs a JSON schema object for the given type argument. |
| 38 | // If non-nil, the provided options configure certain aspects of this contruction, |
| 39 | // described below. |
| 40 | |
| 41 | // It translates Go types into compatible JSON schema types, as follows. |
| 42 | // These defaults can be overridden by [ForOptions.TypeSchemas]. |
| 43 | // |
| 44 | // - Strings have schema type "string". |
| 45 | // - Bools have schema type "boolean". |
| 46 | // - Signed and unsigned integer types have schema type "integer". |
| 47 | // - Floating point types have schema type "number". |
| 48 | // - Slices and arrays have schema type "array", and a corresponding schema |
| 49 | // for items. |
| 50 | // - Maps with string key have schema type "object", and corresponding |
| 51 | // schema for additionalProperties. |
| 52 | // - Structs have schema type "object", and disallow additionalProperties. |
| 53 | // Their properties are derived from exported struct fields, using the |
| 54 | // struct field JSON name. Fields that are marked "omitempty" are |
| 55 | // considered optional; all other fields become required properties. |
| 56 | // - Some types in the standard library that implement json.Marshaler |
| 57 | // translate to schemas that match the values to which they marshal. |
| 58 | // For example, [time.Time] translates to the schema for strings. |
| 59 | // |
| 60 | // For will return an error if there is a cycle in the types. |
| 61 | // |
| 62 | // By default, For returns an error if t contains (possibly recursively) any of the |
| 63 | // following Go types, as they are incompatible with the JSON schema spec. |
| 64 | // If [ForOptions.IgnoreInvalidTypes] is true, then these types are ignored instead. |
| 65 | // - maps with key other than 'string' |
| 66 | // - function types |
| 67 | // - channel types |
| 68 | // - complex numbers |
| 69 | // - unsafe pointers |
| 70 | // |
| 71 | // This function recognizes struct field tags named "jsonschema". |
| 72 | // A jsonschema tag on a field is used as the description for the corresponding property. |
| 73 | // For future compatibility, descriptions must not start with "WORD=", where WORD is a |
| 74 | // sequence of non-whitespace characters. |
| 75 | func For[T any](opts *ForOptions) (*Schema, error) { |
| 76 | if opts == nil { |
| 77 | opts = &ForOptions{} |
| 78 | } |
| 79 | schemas := maps.Clone(initialSchemaMap) |
| 80 | // Add types from the options. They override the default ones. |
| 81 | maps.Copy(schemas, opts.TypeSchemas) |
| 82 | s, err := forType(reflect.TypeFor[T](), map[reflect.Type]bool{}, opts.IgnoreInvalidTypes, schemas) |
| 83 | if err != nil { |
| 84 | var z T |
| 85 | return nil, fmt.Errorf("For[%T](): %w", z, err) |
| 86 | } |
| 87 | return s, nil |
| 88 | } |
| 89 | |
| 90 | // ForType is like [For], but takes a [reflect.Type] |
| 91 | func ForType(t reflect.Type, opts *ForOptions) (*Schema, error) { |
| 92 | schemas := maps.Clone(initialSchemaMap) |
| 93 | // Add types from the options. They override the default ones. |
| 94 | maps.Copy(schemas, opts.TypeSchemas) |
| 95 | s, err := forType(t, map[reflect.Type]bool{}, opts.IgnoreInvalidTypes, schemas) |
| 96 | if err != nil { |
| 97 | return nil, fmt.Errorf("ForType(%s): %w", t, err) |
| 98 | } |
| 99 | return s, nil |
| 100 | } |
| 101 | |
| 102 | func forType(t reflect.Type, seen map[reflect.Type]bool, ignore bool, schemas map[reflect.Type]*Schema) (*Schema, error) { |
| 103 | // Follow pointers: the schema for *T is almost the same as for T, except that |
| 104 | // an explicit JSON "null" is allowed for the pointer. |
| 105 | allowNull := false |
| 106 | for t.Kind() == reflect.Pointer { |
| 107 | allowNull = true |
| 108 | t = t.Elem() |
| 109 | } |
| 110 | |
| 111 | // Check for cycles |
| 112 | // User defined types have a name, so we can skip those that are natively defined |
| 113 | if t.Name() != "" { |
| 114 | if seen[t] { |
| 115 | return nil, fmt.Errorf("cycle detected for type %v", t) |
| 116 | } |
| 117 | seen[t] = true |
| 118 | defer delete(seen, t) |
| 119 | } |
| 120 | |
| 121 | if s := schemas[t]; s != nil { |
| 122 | return s.CloneSchemas(), nil |
| 123 | } |
| 124 | |
| 125 | var ( |
| 126 | s = new(Schema) |
| 127 | err error |
| 128 | ) |
| 129 | |
| 130 | switch t.Kind() { |
| 131 | case reflect.Bool: |
| 132 | s.Type = "boolean" |
| 133 | |
| 134 | case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, |
| 135 | reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, |
| 136 | reflect.Uintptr: |
| 137 | s.Type = "integer" |
| 138 | |
| 139 | case reflect.Float32, reflect.Float64: |
| 140 | s.Type = "number" |
| 141 | |
| 142 | case reflect.Interface: |
| 143 | // Unrestricted |
| 144 | |
| 145 | case reflect.Map: |
| 146 | if t.Key().Kind() != reflect.String { |
| 147 | if ignore { |
| 148 | return nil, nil // ignore |
| 149 | } |
| 150 | return nil, fmt.Errorf("unsupported map key type %v", t.Key().Kind()) |
| 151 | } |
| 152 | if t.Key().Kind() != reflect.String { |
| 153 | } |
| 154 | s.Type = "object" |
| 155 | s.AdditionalProperties, err = forType(t.Elem(), seen, ignore, schemas) |
| 156 | if err != nil { |
| 157 | return nil, fmt.Errorf("computing map value schema: %v", err) |
| 158 | } |
| 159 | if ignore && s.AdditionalProperties == nil { |
| 160 | // Ignore if the element type is invalid. |
| 161 | return nil, nil |
| 162 | } |
| 163 | |
| 164 | case reflect.Slice, reflect.Array: |
| 165 | s.Type = "array" |
| 166 | s.Items, err = forType(t.Elem(), seen, ignore, schemas) |
| 167 | if err != nil { |
| 168 | return nil, fmt.Errorf("computing element schema: %v", err) |
| 169 | } |
| 170 | if ignore && s.Items == nil { |
| 171 | // Ignore if the element type is invalid. |
| 172 | return nil, nil |
| 173 | } |
| 174 | if t.Kind() == reflect.Array { |
| 175 | s.MinItems = Ptr(t.Len()) |
| 176 | s.MaxItems = Ptr(t.Len()) |
| 177 | } |
| 178 | |
| 179 | case reflect.String: |
| 180 | s.Type = "string" |
| 181 | |
| 182 | case reflect.Struct: |
| 183 | s.Type = "object" |
| 184 | // no additional properties are allowed |
| 185 | s.AdditionalProperties = falseSchema() |
| 186 | for _, field := range reflect.VisibleFields(t) { |
| 187 | if field.Anonymous { |
| 188 | continue |
| 189 | } |
| 190 | |
| 191 | info := fieldJSONInfo(field) |
| 192 | if info.omit { |
| 193 | continue |
| 194 | } |
| 195 | if s.Properties == nil { |
| 196 | s.Properties = make(map[string]*Schema) |
| 197 | } |
| 198 | fs, err := forType(field.Type, seen, ignore, schemas) |
| 199 | if err != nil { |
| 200 | return nil, err |
| 201 | } |
| 202 | if ignore && fs == nil { |
| 203 | // Skip fields of invalid type. |
| 204 | continue |
| 205 | } |
| 206 | if tag, ok := field.Tag.Lookup("jsonschema"); ok { |
| 207 | if tag == "" { |
| 208 | return nil, fmt.Errorf("empty jsonschema tag on struct field %s.%s", t, field.Name) |
| 209 | } |
| 210 | if disallowedPrefixRegexp.MatchString(tag) { |
| 211 | return nil, fmt.Errorf("tag must not begin with 'WORD=': %q", tag) |
| 212 | } |
| 213 | fs.Description = tag |
| 214 | } |
| 215 | s.Properties[info.name] = fs |
| 216 | if !info.settings["omitempty"] && !info.settings["omitzero"] { |
| 217 | s.Required = append(s.Required, info.name) |
| 218 | } |
| 219 | } |
| 220 | |
| 221 | default: |
| 222 | if ignore { |
| 223 | // Ignore. |
| 224 | return nil, nil |
| 225 | } |
| 226 | return nil, fmt.Errorf("type %v is unsupported by jsonschema", t) |
| 227 | } |
| 228 | if allowNull && s.Type != "" { |
| 229 | s.Types = []string{"null", s.Type} |
| 230 | s.Type = "" |
| 231 | } |
| 232 | return s, nil |
| 233 | } |
| 234 | |
| 235 | // initialSchemaMap holds types from the standard library that have MarshalJSON methods. |
| 236 | var initialSchemaMap = make(map[reflect.Type]*Schema) |
| 237 | |
| 238 | func init() { |
| 239 | ss := &Schema{Type: "string"} |
| 240 | initialSchemaMap[reflect.TypeFor[time.Time]()] = ss |
| 241 | initialSchemaMap[reflect.TypeFor[slog.Level]()] = ss |
| 242 | initialSchemaMap[reflect.TypeFor[big.Int]()] = &Schema{Types: []string{"null", "string"}} |
| 243 | initialSchemaMap[reflect.TypeFor[big.Rat]()] = ss |
| 244 | initialSchemaMap[reflect.TypeFor[big.Float]()] = ss |
| 245 | } |
| 246 | |
| 247 | // Disallow jsonschema tag values beginning "WORD=", for future expansion. |
| 248 | var disallowedPrefixRegexp = regexp.MustCompile("^[^ \t\n]*=") |