Search code examples
javascriptjsonschemaajv

AJV schema validation for object with unknown properties


I have a funny scenario all over my platform, but I believe it's the best. I am trying to validate a JSON Schema where an object has unknown keys with the same schema as value. The keys are unique ID's and the value of those keys have the same schema.

To understand it, let me explain with a sample code:

let survey_questions = {
  "vv4sD32": {
    question: "Do you like dogs?",
    answers: ["Yes", "No"]
  },
  "df4sdIU": {
    question: "How about cats?",
    answers: ["Maybe", "Maybe not"]
  },
  "cbkle12": {
    question: "What do you prefer most?",
    answers: ["Dogs", "Cats"]
  }
}

As you can see, that sample is a survey, where the key is the unique ID of the question, and the value is an object with a shared schema. I know I could loop though them and check the schema on each individual question, but I have examples of nested things of these type, and would complicate things a lot. Any suggestions how to do this with AJV, or any other library?

Thank you,

Carlino


Solution

  • There are great answers here. At the end, I ended up creating my own library I’ve been using for years and that has become quite popular recently. The library is https://www.npmjs.com/package/great-json-validator checking for the data type “array-object”. The documentation has a very google example.