Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON schema "oneOf" for validating existence of keys

I'm trying to create a JSON schema that validates against multiple different entities that have mostly the same attributes but only differ in a few attributes.

{
  "firstname": "Bat",
  "lastname": "man",
  "email": "[email protected]"
}

{
  "firstname": "Super",
  "lastname": "man",
  "phone": "543-453-4523"
}

{
  "firstname": "Wonderwo",
  "lastname": "man",
  "email": "[email protected]"
}

Basically I want to create a single schema that makes sure the last name is "man" and either have a phone or email attribute.

I was trying to implement this using oneOf, like this:

{
  "properties": {
    "firstname": {
      "type": "string"
    },
    "lastname": {
      "type": "string",
      "pattern": "man"
    },
    "oneOf": [{
      "email": {
        "type": "string"
      },
      "phone": {
        "type": "string"
      }
    }]
  }
}

But I don't think this works. Is something like this even possible with JSON schema? And how can I achieve this?

like image 452
Vlad Avatar asked Jan 23 '26 14:01

Vlad


1 Answers

You have several problems:

  1. "oneOf" is a keyword, in cannot be used inside properties.
  2. items inside "oneOf" should be schemas, what you have there is not.
  3. "anyOf" is almost always better than "oneOf", unless you really need an exclusive "OR"
  4. "pattern" is a wrong keyword here, you need "enum" (or draft-06 "const")

You need:

{
  "type": "object",
  "required": ["firstname", "lastname"],
  "properties": {
    "firstname": {
      "type": "string"
    },
    "lastname": {
      "type": "string",
      "enum": ["man"]
    },
    "email": {
      "type": "string"
    },
    "phone": {
      "type": "string"
    }
  },
  "anyOf": [
    { "required": ["email"] },
    { "required": ["phone"] }
  ]
}
like image 120
esp Avatar answered Jan 26 '26 05:01

esp