I need to validate a JSON object by using a schema to make sure that all the elements specified in the schema are present in the array. For instance, my people array should include the following individuals:
{
"people":[
{
"name":"Bob",
"age":"26"
},
{
"name":"Jim",
"age":"35"
},
{
"name":"John",
"age":"27"
}
]
}
Any extra individuals will be disregarded, but these must exist. I attempted to use allOf in the items specifier, but it didn't work because allOf requires each element to match each of the provided schemas.
{
"people":{
"type":"array",
"items":{
"allOf":[
{
"type":"object",
"properties":{
"name":{
"type":"string",
"const":"Bob"
},
"age":{
"type":"string",
"const":"26"
}
},
"required":[
"name",
"age"
]
},
{
"type":"object",
"properties":{
"name":{
"type":"string",
"const":"Jim"
},
"age":{
"type":"string",
"const":"35"
}
},
"required":[
"name",
"age"
]
},
{
"type":"object",
"properties":{
"name":{
"type":"string",
"const":"John"
},
"age":{
"type":"string",
"const":"27"
}
},
"required":[
"name",
"age"
]
}
]
}
}
}
From this data, it can be determined that a valid people array would consist of:
[
{
"name":"Bob",
"age":"26"
},
{
"name":"Jim",
"age":"35"
},
{
"name":"John",
"age":"27"
}
]
While an invalid array would be:
[
{
"name":"Bob",
"age":"26"
},
{
"name":"Jim",
"age":"35"
},
{
"name":"Tim",
"age":"47"
}
]
since John is missing from the list.
This is the code for the AJV file.
const Ajv = require('ajv');
const jsonInput = require('./people.json');
const schema = require('./peopleSchema.json');
const ajv = new Ajv();
const validate = ajv.compile(schema);
const valid = validate(jsonInput);
console.log(valid);
if (!valid) console.log(validate.errors);
Which property should be used to specify the required elements in an array as mentioned above?
Update: In response to the comment, I attempted to incorporate 'contains' without success.
{
"$id": "root",
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"people": {
"type": "array",
"items": {
"type": "object",
"allOf": [
{
"contains": {
"properties": {
"name": {
"enum": ["Bob"]
},
"age": {
"enum": ["26"]
}
}
}
},
{
"contains": {
"properties": {
"name": {
"enum": ["John"]
},
"age": {
"enum": ["27"]
}
}
}
},
{
"contains": {
"properties": {
"name": {
"enum": ["Jim"]
},
"age": {
"enum": ["36"]
}
}
}
}
]
}
}
},
"required": ["people"]
}