5

I am interested in validating some JSON logic to check for a certain value is in place for for the first element in an array. I would like to achieve this via JSON schema if possible. For Example, I would like to check to see if the first element is "manager":

  "employees": [
    {
      "manager": "Band35",
      "name": "Tom"
    },
    {
      "developer": "Band25",
      "name": "Kelly"
    },
    {
      "analyst": "Band25",
      "name": "Jack"
    }    
  ]
}
jbambrough
  • 597
  • 2
  • 7
  • 15

2 Answers2

6

You can use the items keyword to validate an array.

If "items" is an array of schemas, validation succeeds if each element of the instance validates against the schema at the same position, if any.

This means you should have items: [firstSchema] if you want to check that the first item in your array should pass firstSchema.

For example, if you want the first item in the array to be a specific string...

{
  "items": [
    {
      "type": "string",
      "const": "myFirstItemString"
    }
  ]
}

For checking a specific property name of an object, you need to use propertyNames keyword.

You can test this easily by using https://jsonschema.dev

Relequestual
  • 11,631
  • 6
  • 47
  • 83
-1

Deserialize JSON into an object (depending on language) and check for the value of the "manager" property on the first element of the array, would be helpful if you were more specific on what language or tools you're using (Example in JS below)

var validated = (JSON.parse(json).employees[0].manager === "Band35");

Hope this helps!

Matt Drouillard
  • 199
  • 2
  • 11