Maciek Bergier
Maciek Bergier

Reputation: 13

JSON schema connecting arrays with properties

I've been asked to create JSON Schema with filetype called "zfs" containing array property pools, where each item of such array must have properties: name (string), volumes (array of strings), sizeInGB (number from 0 to 65536), and numberOfFiles (integer from 0 to 4294967296). Code i came up with looks like this,

{
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "zfs",
"type": "array",
 "properties" : {
   "names":{"type": "string"},
   "volumes":{"type": "array"},
     "properties" : {"type": "string"},
         "sizeInGB":{
          "type": "number",
        "minimum": 0,
        "maximum": 65536
         },
         "numberOfFiles":{
          "type": "integer",
        "minimum": 0,
        "maximum": 4294967296
         }
         },
         "required": [ "names", "numberOfFiles","sizeInGB","volumes"],
}

but it throws out EOF errors while validating and even though i'm aware of what that error means i just have no idea how to deal with it to make it work properly.

Upvotes: 1

Views: 3465

Answers (1)

PsychoFish
PsychoFish

Reputation: 1639

Maciek, there might be an issue with your schema. You define:

"type" : "array",
"properties" : {
  "names" : {...},
  "volumes" : {
     "type" : array"
  },
  "properties" : { ...}
}

I understand you want an

array of objects where each objects contains: name and an array of objects

What I would expect to be phrased in JSON Schema as:

"type" : "array",
"items" : {        <============ here
  "type" : "object",
  "properties" : {
    "names" : {...},
    "volumes" : {
      "type" : array"
      "items" : {   <============ and here
        "type" : "object",
        "properties" : { ... }
      }
    },
  },
}

In JSON schema you need somehow define schema of contents of/items in an array (if you want to validate JSON array items against matching JSON schema). You can do it with "items" keyword and either using tuple syntax (if sequence of elements in array is important) or as an array of objects, where sequence is irrelevant but each object must conform to a specific schema. Yep, you can have even an array of different kinds of objects if you need to.

Please read: https://json-schema.org/understanding-json-schema/reference/array.html

and spec for https://json-schema.org/latest/json-schema-validation.html#rfc.section.6.4

Hope it helped.

Upvotes: 2

Related Questions