Skip to content
Advertisement

Json schema validation against Json Object using javascript

I am trying to validate around 100 JSON Objects against a JSON schema to see if all the fields along with the type are as per the schema or not.

Tried below JSON schema which was generated from a site. The issue with the below schema is that it does not support validation of multiple items for the “files” field as the schema is not completely correct.

Added below schema

     var schema ={
  "$schema": "http://json-schema.org/draft-04/schema#",
  "type": "object",
  "properties": {
    "data": {
      "type": "object",
      "properties": {
        "contents": {
          "type": "array",
          "items": [
            {
              "type": "object",
              "properties": {
                "version": {
                  "type": "string"
                },
                "sequence": {
                  "type": "integer"
                },
                "files": {
                  "type": "array",
                  "items": [
                    {
                      "type": "object",
                      "properties": {
                        "fileName": {
                          "type": "string"
                        },
                        "name": {
                          "type": "string"
                        },
                        "fileSize": {
                          "type": "string"
                        },
                        "fileType": {
                          "type": "string"
                        },
                        "lastUpdatedDate": {
                          "type": "integer"
                        },
                        "fileLength": {
                          "type": "integer"
                        },
                        "version": {
                          "type": "integer"
                        }
                      },
                      "required": [
                        "fileName",
                        "name",
                        "fileSize",
                        "fileType",
                        "lastUpdatedDate",
                        "fileLength",
                        "version"
                      ]
                    }
                  ]
                }
              },
              "required": [
                "version",
                "sequence",
                "files"
              ]
            }
          ]
        }
      },
      "required": [
        "contents"
      ]
    }
  },
  "required": [
    "data"
  ]
}

  var validator = new Validator(schema)

  var json=
  {
      "data": {
          "contents": [
              {
                  "versionn": "2021-01-15T16:01:13.475Z",
                  "sequence": 1,
                  "files": [
                      {
                          "fileName": "us-producer-price-index.txt",
                          "name": "us-producer-price-index",
                          "fileSize": "54MB",
                          "fileType": "txt",
                          "lastUpdatedDate": 1610717473000,
                          "fileLength": 56614933,
                          "version": 2
                      }
                  ]
              }
          ]
      }
  };

  var check = validator.check(json);
   
  console.log(check);

  if(check._error==true)
  {
      console.log("Error in schema")
  }

Advertisement

Answer

I assume that what you want is to apply the same validation rule for all the items in your array.

Schema provides list validation and tuple validation. The list validation is specified as a schema, apply the same rule for any item in the array, the tuple is specified as an array of schemas and validate item[i] against schema.item[i].

Notice that your items schemas is an array of one element. This means that only the first element is validated against your schema. What I assume you want instead is this schema.

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "type": "object",
  "properties": {
    "data": {
      "type": "object",
      "properties": {
        "contents": {
          "type": "array",
          "items": {
            "type": "object",
            "properties": {
              "version": {
                "type": "string"
              },
              "sequence": {
                "type": "integer"
              },
              "files": {
                "type": "array",
                "items": {
                  "type": "object",
                  "properties": {
                    "fileName": {
                      "type": "string"
                    },
                    "name": {
                      "type": "string"
                    },
                    "fileSize": {
                      "type": "string"
                    },
                    "fileType": {
                      "type": "string"
                    },
                    "lastUpdatedDate": {
                      "type": "integer"
                    },
                    "fileLength": {
                      "type": "integer"
                    },
                    "version": {
                      "type": "integer"
                    }
                  },
                  "required": [
                    "fileName",
                    "name",
                    "fileSize",
                    "fileType",
                    "lastUpdatedDate",
                    "fileLength",
                    "version"
                  ]
                }
              }
            },
            "required": [
              "version",
              "sequence",
              "files"
            ]
          }
        }
      },
      "required": [
        "contents"
      ]
    }
  },
  "required": [
    "data"
  ]
}

Additional examples

In order to illustrate the how the array validation works I created a snipped that is very enlightening.

const Ajv = window.ajv7.default;
const ajv = new Ajv({strict: false});

function dumpJson(item){
  const el = document.createElement('pre');
  el.textContent = typeof(item) === 'string' ? item :  JSON.stringify(item)
  document.body.appendChild(el);
  return el;
}

function Test(schema, title){
  const validate = ajv.compile(schema)
  if(title)dumpJson(title).classList.add('title')
  dumpJson(JSON.stringify(schema, null, 2))
  const tester = {
    with: (item) => {
      const el = dumpJson(item)
      if(validate(item)){
        el.classList.add('valid');
      }else{
        el.classList.add('invalid');
      }
      return tester
    }
  }
  return tester;
}

Test({
  "$schema": "http://json-schema.org/draft-07/schema#",
  type: 'array', items: [{type: 'number'}, {type: 'string'}]
}, 'tuple validation: [number]')
.with([0])
.with([0, 1])
.with([0, "a"])
.with([0, "a", {}, [], null, false, true])
Test({
  "$schema": "http://json-schema.org/draft-07/schema#",
  type: 'array', items: [{type: 'number'}]
}, 'tuple validation: [number, string]')
.with([0])
.with([0, 1])
.with([0, "a"])
.with([0, "a", {}, [], null, false, true])

Test({
  "$schema": "http://json-schema.org/draft-07/schema#",
  type: 'array', items: {type: 'number'}
}, 'list validation: number[]')
.with([0])
.with([0, 1])
.with([0, "a"])
.with([0, "a", {}, [], null, false, true])


Test({
  "$schema": "http://json-schema.org/draft-07/schema#",
  type: 'array', items: [{type: 'number'}, {type: 'string'}]
}, 'tuple validation: [number, string]')
.with([0])
.with([0, 1])
.with([0, "a"])
.with([0, "a", {}, [], null, false, true])

Test({
  "$schema": "http://json-schema.org/draft-07/schema#",
  type: 'array', items: {'anyOf': [{type: 'number'}, {type: 'string'}]}
}, 'list validation: (number|string)[]')
.with([0])
.with([0, 1])
.with([0, "a"])
.with([0, "a", {}, [], null, false, true])
.with(['a', 'b', 'c'])
.with(['a', 0])
.with(['a', 0, false])
.valid {
  margin-left: 20px; color: green;
}
.invalid {
  margin-left: 20px; color: red;
}
.title {
  font-size: 2em;
}

body: {
  overflow: scroll;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/ajv/7.1.1/ajv7.min.js"></script>
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement