Search code examples
jsonjsonschema

How to validate all items of JSON array have exactly the same field value using JSON Schema?


Let's say we have the following JSON Schema:

{
    "type": "array",
    "items": {
      "type": "object",
      "properties": {
        "name": { "enum": ["Adam", "Daniel", "Mike"] },
        "desc": { "type": ["string", "null"] }
      },
      "required": [
        "name"
      ]
    }
}

Is it possible to validate that the field "name" has the same value for all objects in the array?

Examples:

  1. Valid
[
  {"name": "Adam"},
  {"name": "Adam", "desc": "good"},
]
  1. Valid
[
  {"name": "Mike"},
  {"name": "Mike", "desc": "good"},
]
  1. Invalid
[
  {"name": "Adam"},
  {"name": "Adam", "desc": "good"},
  {"name": "Mike", "desc": "bad"},
]

Solution

  • If you have an explicit list of possible values, as you've shown (i.e. "enum": ["Adam", "Daniel", "Mike"]), then it's possible, but a bit verbose. You'd use an anyOf.

    {
      "type": "array",
      "items": {
        "type": "object",
        "properties": {
            "desc": { "type": ["string", "null"] }
          },
          "required": [
            "name"
          ]
      },
      "anyOf": [
        {
          "items": {
            "properties": {
              "name": { "const": "Adam" }
            }
          } 
        },
        {
          "items": {
            "properties": {
              "name": { "const": "Daniel" }
            }
          } 
        },
        {
          "items": {
            "properties": {
              "name": { "const": "Mike" }
            }
          } 
        }
      ]
    }
    

    This will ensure that all of the items are one of these three values and they're all the same.

    I'd also delete the name property from the /items/properties keywrod as it's not necessary since you're explicitly listing the possible values in the anyOf.

    (Verified with my online playground, https://json-everything.net/json-schema)


    If you're looking to do this with open-ended data, no, JSON Schema doesn't support that.