Replies: 4 comments
-
You can do this with custom vocabulary. but currently there is no api provided to get value location. I just added this api in 055b208 below is sample code for such vocabulary: package jsonschema_test
import (
"fmt"
"log"
"strings"
"github.com/santhosh-tekuri/jsonschema/v6"
)
// SchemaExt --
type deprecated bool
func (d deprecated) Validate(ctx *jsonschema.ValidatorContext, v any) {
fmt.Printf("deprecated: /%s", strings.Join(ctx.ValueLocation(), "/"))
}
// Vocab --
func deprecatedVocab() *jsonschema.Vocabulary {
url := "http://example.com/meta/discriminator"
schema, err := jsonschema.UnmarshalJSON(strings.NewReader(`{
"properties" : {
"deprecated": {
"type": "boolean"
}
}
}`))
if err != nil {
log.Fatal(err)
}
c := jsonschema.NewCompiler()
if err := c.AddResource(url, schema); err != nil {
log.Fatal(err)
}
sch, err := c.Compile(url)
if err != nil {
log.Fatal(err)
}
return &jsonschema.Vocabulary{
URL: url,
Schema: sch,
Compile: compileDeprecated,
}
}
func compileDeprecated(ctx *jsonschema.CompilerContext, obj map[string]any) (jsonschema.SchemaExt, error) {
v, ok := obj["deprecated"]
if !ok {
return nil, nil
}
b, ok := v.(bool)
if !ok {
return nil, nil
}
return deprecated(b), nil
}
// Example --
func Example_vocab_deprecated() {
schema, err := jsonschema.UnmarshalJSON(strings.NewReader(`{
"properties": {
"email": {
"type": "string",
"deprecated": true
}
}
}`))
if err != nil {
fmt.Println("xxx", err)
log.Fatal(err)
}
inst, err := jsonschema.UnmarshalJSON(strings.NewReader(`{
"email": "[email protected]"
}`))
if err != nil {
log.Fatal(err)
}
c := jsonschema.NewCompiler()
c.AssertVocabs()
c.RegisterVocabulary(deprecatedVocab())
if err := c.AddResource("schema.json", schema); err != nil {
log.Fatal(err)
}
sch, err := c.Compile("schema.json")
if err != nil {
log.Fatal(err)
}
err = sch.Validate(inst)
if err != nil {
log.Fatal(err)
}
// Output:
// deprecated: /email
} this prints deprecated location in instance as jsonpaths |
Beta Was this translation helpful? Give feedback.
-
converted from issue to discussion |
Beta Was this translation helpful? Give feedback.
-
HI @santhosh-tekuri thank you. Any way to reuse "deprecationMessage" instead of introducing another property? |
Beta Was this translation helpful? Give feedback.
-
you can capture value of |
Beta Was this translation helpful? Give feedback.
-
Hi, is it possible to hook into field usage with the library? I'd like to log a message when deprecated fields are used. Thank you.
Beta Was this translation helpful? Give feedback.
All reactions