1
votes

I need to create a JSON schema for data that comes as an array directly within the root object, unnamed. An MWE for this kind of JSON would be:

{
  [ 
    {
      "veggieName": "potato",
      "veggieLike": true
    },
    {
      "veggieName": "broccoli",
      "veggieLike": false
    }
  ]
}

I have seen examples for schemas which validate such an array which is not nested in an object. I have also seen examples which work when the array is named, for example

{
  vegetables : [ 
    {
      "veggieName": "potato",
      "veggieLike": true
    },
    {
      "veggieName": "broccoli",
      "veggieLike": false
    }
  ]
}

This second example can be validated by the schema

{
  "$id": "https://example.com/arrays.schema.json",
  "$schema": "http://json-schema.org/draft-07/schema#",
  "description": "A representation of a person, company, organization, or place",
  "type": "object",
  "properties": {
    "vegetables": {
      "type": "array",
      "items": { "$ref": "#/definitions/veggie" }
    }
  },
  "definitions": {
    "veggie": {
      "type": "object",
      "required": [ "veggieName", "veggieLike" ],
      "properties": {
        "veggieName": {
          "type": "string",
          "description": "The name of the vegetable."
        },
        "veggieLike": {
          "type": "boolean",
          "description": "Do I like this vegetable?"
        }
      }
    }
  }
}

But the problem is, as soon as the name "vegetables" is removed, I was not able to find a way to define a valid schema. How do I properly represent my data structure in a schema?

(MWEs derived from http://json-schema.org/learn/miscellaneous-examples.html).

1
A duplicate based on title but not on content. Other question showed they used a schema which defined the root element must be an array, this question does not.Relequestual
Good point @Relequestual I have retracted the close vote.tom redfern

1 Answers

2
votes

The schema you are looking for is the following:

{
   "$id":"https://example.com/arrays.schema.json",
   "$schema":"http://json-schema.org/draft-07/schema#",
   "description":"A representation of a person, company, organization, or place",
   "type":"array",
   "items":{
      "type":"object",
      "required":[
         "veggieName",
         "veggieLike"
      ],
      "properties":{
         "veggieName":{
            "type":"string",
            "description":"The name of the vegetable."
         },
         "veggieLike":{
            "type":"boolean",
            "description":"Do I like this vegetable?"
         }
      }
   }
}

You also need to modify your base array instance, your original one (the "unnamed" array) was not valid JSON:

[
   {
      "veggieName":"potato",
      "veggieLike":true
   },
   {
      "veggieName":"broccoli",
      "veggieLike":false
   }
]

Unlike XML, where you are allowed a single root node per document only, in JSON you can have either a type or an array as a root type.