Home > Net >  Golang invopop jsonschema usage of if/then/else
Golang invopop jsonschema usage of if/then/else

Time:09-30

I'm using the library invopop/jsonschema for generating our json-schema based on go struct tags. But I struggle on how to use the if/then/else attributes.

I was doing something like this

type Boulou struct {
    Name              string                   `json:"name" jsonschema:"required,minLength=1,description=unique name"`
    Transformers      []TransformerConfig `json:"transformers" jsonschema:"title=transformers,if=properties.kind.const=convert_swim,then=required[0]=convert_swim_config"`
}

But does not seems to work (i made a go playground if you would like to play with).

Thanks in advance !

Resources:

CodePudding user response:

These complex use-cases aren't supported all that well using Go tags in invopop/jsonschema. Anything that breaks out of regular use-cases I'd recommend implementing the JSONSchema() method so you can define the object manually. Following your example:

type Boulou struct {
    Name              string              `json:"name"`
    Transformers      []TransformerConfig `json:"transformers"`
}

func (Boulou) JSONSchema() *jsonschema.Schema {
  props = orderedmap.New()
  props.Set("name", &jsonschema.Schema{
    Type: "string",
    Title: "Name",
  })
  props.Set("transformers", &jsonschema.Schema{
    Type: "array",
    Title: "Transformers",
    Items: &jsonschema.Schema{
      Ref:  ".....",
      If:   "properties.kind.const=convert_swim",
      Then: "required[0]=convert_swim_config",
    },
  })
  return &jsonschema.Schema{
    Type:       "object",
    Title:      "Boulou",
    Properties: props,
  }
}

I haven't tested this directly, but I'm sure you get the idea. You'll need to figure out what the Ref for your TransformerConfig is manually.

  • Related