ajv
ajv copied to clipboard
[JTD] unions do not work with ajv.compileParser
What version of Ajv are you using? 8.11.0 with JTD
Issue description
I created a simple JTD schema using the union keyword.
When I use it with Validate Function created with ajv.compile everything seems to work correctly (in my example field accepts string and boolean).
Unfortunately, when I use it with ajv.compileParser instance union metadata seems to be omitted and invalid data is parsed without errors.

What results did you expect?
I expected that using ajv.compile and ajv.compileParser with the same schema will validate data in the same way.
Are you going to resolve the issue?
For now, I decided to firstly parse the string with a parser created with ajv.compileParser and then validate the object with a validator created with ajv.compile. It's not performant, looks suspicious, but seems to work.
Your code
import Ajv from 'ajv/dist/jtd';
const schema = {
properties: {
field: {
metadata: {
union: [{ type: 'string' }, { type: 'boolean' }],
},
},
},
}
const ajv = new Ajv();
const data = { field: 10000 };
// Compile
const compileInstance = ajv.compile(schema);
const resultCompile = compileInstance(data)
console.log(resultCompile);
console.log(compileInstance.errors);
// Parser
const parserInstance = ajv.compileParser(schema);
const resultParser = parserInstance(JSON.stringify(data));
console.log(resultParser);
console.log(parserInstance);
This is not a bug.
Parsers do not parse the string as an object first and then validate them, they use schema to define the expected shape of the data and parse efficiently, and this is at least complex or not possible for unions (or some other non-standard keywords).
If you need to use non-standard JTD keywords, you would have to parse using JSON.parse and then validate separately.
The note needs to be added to the docs.
Thank you @epoberezkin for clarification! 👍
I can add it to the docs. Is this the right place to add the note? https://ajv.js.org/json-type-definition.html#user-defined-keywords