2

I'm trying to figure out how to set a global-level array required in schema. My example JSON file is:

[
    {
        "firstname": "Paul",
        "lastname": "McCartney"
    },
    {
        "firstname": "John",
        "lastname": "Lennon"
    },
    {
        "firstname": "George",
        "lastname": "Harrison"
    },
    {
        "firstname": "Ringo",
        "lastname": "Starr"
    }
]

As seen above, I want the top-level structure to be an array, not an object. The schema I've got from jsonschema.net is (with slight modifications):

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "id": "/",
  "type": "array",
  "items": {
    "id": "elements",
    "type": "object",
    "properties": {
      "firstname": {
        "id": "firstname",
        "type": "string"
      },
      "lastname": {
        "id": "lastname",
        "type": "string"
      }
    },
    "required": [
      "firstname",
      "lastname"
    ]
  },
  "required": [
    "/"
  ]
}

But it fails with the jsonschema validator. Can you please help me with providing correct JSON schema for top-level array?

1
  • 1
    You don't need to make the top-level thing required. If the document is an array, then the document isn't optional! If you're trying to specify a minimum number of items, try minItems. Commented Mar 10, 2015 at 13:13

1 Answer 1

5

To be valid with your input data you just need following schema:

{
    "$schema": "http://json-schema.org/draft-04/schema#",
    "type": "array",
    "id": "http://jsonschema.net",
    "items": {
        "type": "object",
        "properties": {
        "firstname": {
            "type": "string"
        },
        "lastname": {
            "type": "string"
        }
    },
    "required": [
        "firstname",
        "lastname"
    ]}
}
Sign up to request clarification or add additional context in comments.

2 Comments

hmm, I get it - I had useless top-level required field defined. The array-element-level required is enough. Perfect, thanks!
i am using check-jsonschema and required should be a field OF items, not on the same level WITH items

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.