Home > Blockchain >  Python - Validate all rows in JSON file against schema
Python - Validate all rows in JSON file against schema

Time:03-07

I am trying to validate all rows in my JSON data file against the schema without looping through each data entry in the JSON file.

However when just passing in the entire JSON file no validation errors are returned. When looping through each row in the JSON file, the validation works as expected.

I included both validations, the first is how I'd like to validate but is not working as expected. The second validation works but I don't want to loop.

Python code:

import json
from jsonschema import validate

data = [
    {
        "Col1":"asd",
        "Col2":"awer",
        "Col3":"xyz"
    },
    {
        "Col1":"asd",
        "Col2":"awer",
        "Col3":123
    }
]

schema = {
    "title": "test",
    "properties":{
                "Col1" : {
                    "minLength": 0,
                    "maxLength": 15,
                    "type": "string"
                },
                "Col2" : {
                    "minLength": 0,
                    "maxLength": 15,
                    "type": "string"
                },
                "Col3" : {
                    "minLength": 0,
                    "maxLength": 15,
                    "type": "string"
                }

    }
}

# Does not return an error
validate(instance=data, schema=schema)

# Works as expected
for i in range(0,2):
    validate(instance=data[i], schema=schema)

CodePudding user response:

Your JSON schema does not define a top-level array to be expected in your data so the validator does not validate any input at all. If you pass the single objects (array items), your defined properties are validated.

The solution is to put your schema in the items keyword as part of a top-level schema defining your data array.

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "description": "JSON schema generated with JSONBuddy https://www.json-buddy.com",
  "title": "",
  "type": "array",
  "items": {
    "type": "object",
    "properties": {
      "Col1": {
        "minLength": 0,
        "maxLength": 15,
        "type": "string"
      },
      "Col2": {
        "minLength": 0,
        "maxLength": 15,
        "type": "string"
      },
      "Col3": {
        "minLength": 0,
        "maxLength": 15,
        "type": "string"
      }
    }
  }
}
  • Related