### Example JSON Schema Output with Go Comments as Descriptions Source: https://github.com/invopop/jsonschema/blob/main/README.md This JSON schema illustrates the output generated by the `jsonschema` library when `AddGoComments` is used. It shows how Go comments from the `User` struct are transformed into `description` fields within the `$defs/User` object and its properties, demonstrating automatic documentation generation. ```JSON { "$schema": "http://json-schema.org/draft/2020-12/schema", "$ref": "#/$defs/User", "$defs": { "User": { "required": ["id"], "properties": { "id": { "type": "integer", "description": "Unique sequential identifier." }, "name": { "type": "string", "description": "Name of the user" } }, "additionalProperties": false, "type": "object", "description": "User is used as a base to provide tests for comments." } } } ``` -------------------------------- ### Example JSON Schema Output with Custom Snake Case Key Naming Source: https://github.com/invopop/jsonschema/blob/main/README.md This JSON schema illustrates the effect of applying a `KeyNamer` (specifically `strcase.SnakeCase`) during schema generation. It shows how the `GivenName` field is transformed to `given_name` in the `properties` and `required` arrays, while `salted_password` (which had a `json` tag) remains unchanged, demonstrating the `KeyNamer`'s behavior. ```JSON { "$schema": "http://json-schema.org/draft/2020-12/schema", "$ref": "#/$defs/User", "$defs": { "User": { "properties": { "given_name": { "type": "string" }, "salted_password": { "type": "string", "contentEncoding": "base64" } }, "additionalProperties": false, "type": "object", "required": ["given_name", "salted_password"] } } } ``` -------------------------------- ### Define Custom JSON Schema for Go Structs with CompactDate Example Source: https://github.com/invopop/jsonschema/blob/main/README.md Demonstrates how to implement custom JSON marshalling/unmarshalling for a `CompactDate` struct and provide a custom JSON schema definition using the `JSONSchema()` method. This prevents auto-generation and allows a specific pattern for a 'CompactDate' string representation (e.g., 'YYYY-MM'). ```go type CompactDate struct { Year int Month int } func (d *CompactDate) UnmarshalJSON(data []byte) error { if len(data) != 9 { return errors.New("invalid compact date length") } var err error d.Year, err = strconv.Atoi(string(data[1:5])) if err != nil { return err } d.Month, err = strconv.Atoi(string(data[7:8])) if err != nil { return err } return nil } func (d *CompactDate) MarshalJSON() ([]byte, error) { buf := new(bytes.Buffer) buf.WriteByte('"') buf.WriteString(fmt.Sprintf("%d-%02d", d.Year, d.Month)) buf.WriteByte('"') return buf.Bytes(), nil } func (CompactDate) JSONSchema() *Schema { return &Schema{ Type: "string", Title: "Compact Date", Description: "Short date that only includes year and month", Pattern: "^[0-9]{4}-[0-1][0-9]$", } } ``` -------------------------------- ### Reflecting Go Structs to JSON Schema with Custom Tags Source: https://github.com/invopop/jsonschema/blob/main/README.md Demonstrates the reflection of a Go struct, `TestUser`, into a JSON Schema. It showcases how `json`, `jsonschema`, `jsonschema_description`, and `jsonschema_extras` tags are used to define schema properties like `id`, `name` (with title, description, default, examples), `friends` (array with description), `tags` (object with custom extras), `birth_date` and `year_of_birth` (with `oneof_required`), `metadata` (with `oneof_type`), and `fav_color` (with `enum`). The snippet also includes the Go code snippet used to perform the reflection. ```go type TestUser struct { ID int `json:"id"` Name string `json:"name" jsonschema:"title=the name,description=The name of a friend,example=joe,example=lucy,default=alex"` Friends []int `json:"friends,omitempty" jsonschema_description:"The list of IDs, omitted when empty"` Tags map[string]interface{} `json:"tags,omitempty" jsonschema_extras:"a=b,foo=bar,foo=bar1"` BirthDate time.Time `json:"birth_date,omitempty" jsonschema:"oneof_required=date"` YearOfBirth string `json:"year_of_birth,omitempty" jsonschema:"oneof_required=year"` Metadata interface{} `json:"metadata,omitempty" jsonschema:"oneof_type=string;array"` FavColor string `json:"fav_color,omitempty" jsonschema:"enum=red,enum=green,enum=blue"` } ``` ```go jsonschema.Reflect(&TestUser{}) ``` ```json { "$schema": "https://json-schema.org/draft/2020-12/schema", "$id": "https://github.com/invopop/jsonschema_test/test-user", "$ref": "#/$defs/TestUser", "$defs": { "TestUser": { "oneOf": [ { "required": ["birth_date"], "title": "date" }, { "required": ["year_of_birth"], "title": "year" } ], "properties": { "id": { "type": "integer" }, "name": { "type": "string", "title": "the name", "description": "The name of a friend", "default": "alex", "examples": ["joe", "lucy"] }, "friends": { "items": { "type": "integer" }, "type": "array", "description": "The list of IDs, omitted when empty" }, "tags": { "type": "object", "a": "b", "foo": ["bar", "bar1"] }, "birth_date": { "type": "string", "format": "date-time" }, "year_of_birth": { "type": "string" }, "metadata": { "oneOf": [ { "type": "string" }, { "type": "array" } ] }, "fav_color": { "type": "string", "enum": ["red", "green", "blue"] } }, "additionalProperties": false, "type": "object", "required": ["id", "name"] } } } ``` -------------------------------- ### Configuring JSON Schema Reflection with ExpandedStruct Source: https://github.com/invopop/jsonschema/blob/main/README.md Illustrates the effect of the `ExpandedStruct` configuration option on JSON Schema generation. When `ExpandedStruct` is set to `true` on a `jsonschema.Reflector` instance, the top-level struct's properties are directly included in the root of the schema instead of being referenced in the `$defs` section. This example also demonstrates how private, ignored, and untagged fields are handled during reflection, ensuring only relevant fields are included and required. ```go type GrandfatherType struct { FamilyName string `json:"family_name" jsonschema:"required"` } type SomeBaseType struct { SomeBaseProperty int `json:"some_base_property"` // The jsonschema required tag is nonsensical for private and ignored properties. // Their presence here tests that the fields *will not* be required in the output // schema, even if they are tagged required. somePrivateBaseProperty string `json:"i_am_private" jsonschema:"required"` SomeIgnoredBaseProperty string `json:"-" jsonschema:"required"` SomeSchemaIgnoredProperty string `jsonschema:"-,required"` SomeUntaggedBaseProperty bool `jsonschema:"required"` someUnexportedUntaggedBaseProperty bool Grandfather GrandfatherType `json:"grand"` } ``` ```json { "$schema": "http://json-schema.org/draft/2020-12/schema", "required": ["some_base_property", "grand", "SomeUntaggedBaseProperty"], "properties": { "SomeUntaggedBaseProperty": { "type": "boolean" }, "grand": { "$schema": "http://json-schema.org/draft/2020-12/schema", "$ref": "#/definitions/GrandfatherType" }, "some_base_property": { "type": "integer" } }, "type": "object", "$defs": { "GrandfatherType": { "required": ["family_name"], "properties": { "family_name": { "type": "string" } }, "additionalProperties": false, "type": "object" } } } ``` -------------------------------- ### Generate JSON Schema from Go Struct with Comments Source: https://github.com/invopop/jsonschema/blob/main/README.md This Go code snippet shows how to use the `Reflector` from the `jsonschema` library to generate a JSON schema from a Go struct. It specifically demonstrates the use of `AddGoComments` to parse Go files and automatically include Go comments as descriptions in the resulting JSON schema. The `github.com/invopop/jsonschema` module path and local directory are provided for comment parsing. ```Go r := new(Reflector) if err := r.AddGoComments("github.com/invopop/jsonschema", "./"); err != nil { // deal with error } s := r.Reflect(&User{}) // output ``` -------------------------------- ### Define Go Struct with Comments for JSON Schema Descriptions Source: https://github.com/invopop/jsonschema/blob/main/README.md This Go struct `User` demonstrates how comments above struct fields and the struct definition itself can be used by the `jsonschema` library to automatically populate the `description` fields in the generated JSON schema. The `ID` field also includes a `json` tag for custom naming and a `jsonschema` tag for required validation. ```Go package main // User is used as a base to provide tests for comments. type User struct { // Unique sequential identifier. ID int `json:"id" jsonschema:"required"` // Name of the user Name string `json:"name"` } ``` -------------------------------- ### Generated JSON Schema for CompactDate Struct Source: https://github.com/invopop/jsonschema/blob/main/README.md The resulting JSON schema definition generated for the `CompactDate` struct, demonstrating how the custom `JSONSchema()` method's output is incorporated into the final schema, defining it as a string with a specific pattern. ```json { "$schema": "http://json-schema.org/draft/2020-12/schema", "$ref": "#/$defs/CompactDate", "$defs": { "CompactDate": { "pattern": "^[0-9]{4}-[0-1][0-9]$", "type": "string", "title": "Compact Date", "description": "Short date that only includes year and month" } } } ``` -------------------------------- ### JSON Schema Customization Methods Source: https://github.com/invopop/jsonschema/blob/main/README.md Details the four methods recognized by the library for customizing JSON schema generation for Go structs. These methods allow developers to provide custom schema definitions, extend auto-generated schemas, alias types, or provide alternative objects for property conversion. Note that all methods must be defined on a non-pointer object. ```APIDOC JSONSchema(): Purpose: Prevents auto-generation of the schema so that you can provide your own definition. Returns: *Schema JSONSchemaExtend(schema *jsonschema.Schema): Purpose: Will be called after the schema has been generated, allowing you to add or manipulate the fields easily. Parameters: schema: *jsonschema.Schema - The schema that has been generated. JSONSchemaAlias(): Purpose: Is called when reflecting the type of object and allows for an alternative to be used instead. Returns: any JSONSchemaProperty(prop string): Purpose: Will be called for every property inside a struct giving you the chance to provide an alternative object to convert into a schema. Parameters: prop: string - The name of the property. Returns: any ``` -------------------------------- ### Define Go Struct for Custom JSON Key Naming Source: https://github.com/invopop/jsonschema/blob/main/README.md This Go struct `User` is used to demonstrate custom key naming in JSON schema generation. It includes fields with default PascalCase names and one field `PasswordSalted` that explicitly uses a `json` tag to define its JSON key as `salted_password`, showcasing how `KeyNamer` interacts with existing tags. ```Go type User struct { GivenName string PasswordSalted []byte `json:"salted_password"` } ``` -------------------------------- ### Apply Custom Key Naming to JSON Schema Generation in Go Source: https://github.com/invopop/jsonschema/blob/main/README.md This Go code snippet demonstrates how to use the `KeyNamer` option of the `jsonschema.Reflector` to transform Go struct field names into a different casing (e.g., snake_case) in the generated JSON schema. It utilizes `strcase.SnakeCase` from `github.com/stoewer/go-strcase` to automatically convert PascalCase field names to snake_case, reducing the need for explicit `json` tags. ```Go r := new(jsonschema.Reflector) r.KeyNamer = strcase.SnakeCase // from package github.com/stoewer/go-strcase r.Reflect(&User{}) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.