Usage instructions perhaps?
GabenGar opened this issue · 8 comments
The docs are pretty sparse on how to actually use it for validation.
So I create a compiler then what? How do I feed it the other json schemas? How do I validate actual jsons? Can I assert a type of parsed JSON with this? Can I extend Compiler
struct to have my own $id
/$ref
parsing logic?
godoc contains examples showing the usage.
if your schema file uses other schema files, they are automatically located and compiled. for example consider following schema file /example/schema1.json
with content:
{
"properties": {
"p1": {
"type": "boolean"
},
"p2": {
"$ref": "schema2.json"
}
}
}
and /example/schema2.json
has following content:
{
"type": "string"
}
then to compile the schema do the following:
sch, err := jsonschema.Compile("/example/schema1.json")
if err != nil {
log.Fatalf("%#v", err)
}
you can see that you are compiling /example/schema1.json
. the compiler automatically located /example/schema2.json
and compiles it.
to validate `/example/sample.json', do the following:
data, err := ioutil.ReadFile("/example/sample.json")
if err != nil {
log.Fatal(err)
}
var v interface{}
if err := json.Unmarshal(data, &v); err != nil {
log.Fatal(err)
}
if err = sch.Validate(v); err != nil {
log.Fatalf("%#v", err)
}
if you want to locate with your own logic, use jsonschema.Loaders
see example
Yeah but I am using draft7
so I have to go custom Compiler
route. Do I understand it right I'll have to use Compiler.AddResource()
to add json schemas and then Compiler.MustCompile()
to create schemas out of them?
if the subschema is not in the expected location then Compiler.AddResource()
has to be used.
say in the above example the compiler looks for schema2.json
at location /example/schema2.json
. for example say schema2.json
is in directory /somedir/schema2.json
file, then you have to do the following:
schema2, err := ioutil.ReadFile("/somedir/schema2.json")
if err != nil {
log.Fatal(err)
}
compiler.AddResource("file:///example/schema2.json", schema2)
But reading from file system is sub-optimal and a security issue at runtime (i.e. the user machine can change schemas in-between program restarts).
Let's say I used codegen to create a map of schemas map[string][]byte
, where key is $id
of the schema and the value is its json literal converted into bytes.
How do I convert this map into the map/list of schemas usable by this package?
this example demonstrates how to load schemas from map
The readme mentions schema introspection, does the package provide a way to generate types/structs/interfaces from the schemas?
The Schema struct is exported in api. Gererating what you said can be implemented using the information in Schema struct