json-schema
json-schema copied to clipboard
How to make a schema from inline?
I really can't figure out how to just import a schema that's defined inline. How do I load a simple schema and then execute it using this library without using abolute paths or host it online?
const JsonSchema = require("@hyperjump/json-schema");
const sch = JSON.parse(`{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://somesite.com/schema/base",
"type": "object",
"title": "This is the outer doc",
"properties": {
"version": { "type": "string" },
"info": { "$ref": "/schema/info" }
},
"required": ["version", "info"],
"$defs": {
"info": {
"$id": "/schema/info",
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "object",
"properties": {
"issuer": { "type": "string" }
},
"required": ["issuer"]
}
}
}`)
const input = {
"version": "test",
"info": { "issuer": "test" },
}
JsonSchema.validate(sch, input).then(console.log).catch(console.error)
JsonSchema.validate
doesn't take a raw schema, it takes a SchemaDocument instance. You need to use JsonSchema.add
to load your schema into the system, then use JsonSchema.get
to get a SchemaDocument for that schema.
JsonSchema.add(sch);
const schema = await JsonSchema.get("https://somesite.com/schema/base");
const output = await JsonSchema.validate(schema, input);
Sorry that was confusing. I have considered having JsonSchema.validate
optionally take a URI instead of a SchemaDocument. That would cut down on the boilerplate code in cases like this.