invopop / jsonschema

Generate JSON Schemas from Go types
MIT License
537 stars 87 forks source link

Adding maxItems to a custom array type in JSON schema #144

Open LazarenkoA opened 5 months ago

LazarenkoA commented 5 months ago

I have the following Go structure:

type CustomTypes []CustomType

type test struct {
    Field1 CustomTypes `json:"field1"`
}

This generates the following JSON schema:

{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "https://stash.sigma.sbrf.ru/scpl/core.agentserver/pkg/app/test",
  "$ref": "#/$defs/test",
  "$defs": {
    "CustomType": {
      "properties": {},
      "additionalProperties": false,
      "type": "object"
    },
    "CustomTypes": {
      "items": {
        "$ref": "#/$defs/CustomType"
      },
      "type": "array"
    },
    "test": {
      "properties": {
        "field1": {
          "$ref": "#/$defs/CustomTypes"
        }
      },
      "additionalProperties": false,
      "type": "object",
      "required": [
        "field1"
      ]
    }
  }
}

I need to add a maxItems constraint to the CustomTypes array, for example:

"CustomTypes": {
      "items": {
        "$ref": "#/$defs/CustomType"
      },
      "type": "array",
      "maxItems": 10
    }

How can I achieve this? I can't add a tag to the type definition in Go.

Rosswell commented 4 months ago

@LazarenkoA - i believe this is working - try to add this tags to your struct:

type CustomTypes []CustomType

type test struct {
    Field1 CustomTypes `json:"field1" jsonschema:"maxItems=10"`
}

it also supports minItems in the same way

LazarenkoA commented 4 months ago

@Rosswell so it adds here "field1": { "$ref": "#/$defs/CustomTypes", "maxItems": 10 }

but it needs to be in the type