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"
    }    
  ]
}

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

1 Comment

Note in the latest draft, items now needs to be prefixitems for tuple validation like this
-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!

2 Comments

OP said they wanted to use JSON Schema, which is language agnostic.
You're correct, thanks for the clarification on my part :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.