i maed dis
i maed dis

Reputation: 184

JSON schema, validate that only one object in array has property equals to value

I have a payload that i want to validate using JSON schema, but there this case that i don't know how to translate to a schema.

Let's say i have this object:

{
  jobs: [
    { title: "Developer", salary: "100", actual: false },
    { title: "Plumber", salary: "200", actual: true },
    { title: "Teacher", salary: "100", actual: false }
  ]
}

i want to write a schema that validates that IF there are objects in the jobs array, one (and only one) of them MUST have the actual key set to true.

Is this possible?

Upvotes: 1

Views: 1103

Answers (1)

Ether
Ether

Reputation: 54014

Yes, it's possible. You want to set up a schema with the "items", "contains", "minContains" and "maxContains" keywords that leverage the "if"/"then" ability to write conditionals. That is, in pseudocode:

  • I have an object with property "jobs", whose value must be an array.
  • the items in that array are objects, which have properties named "title", "salary" and "actual" (with specific types for each of those values).
  • either the "jobs" array has zero items, or it must contain exactly one item which has a property named "actual" whose value is a constant of value true.

Upvotes: 1

Related Questions