Swatcat
Swatcat

Reputation: 37

Python JSON schema validation for array of objects

I am trying to validate a JSON file using the schema listed below, I can enter any additional fields, I don't understand, what I am doing wrong and why please?

Sample JSON Data

{
    "npcs":
    [
        {
            "id": 0,
            "name": "Pilot Alpha",
            "isNPC": true,
            "race": "1e",
            "testNotValid": false
        },
        {
            "id": 1,
            "name": "Pilot Beta",
            "isNPC": true,
            "race": 1
        }
    ]
}

JSON Schema

I have set "required" and "additionalProperties" so I thought the validation would fail....

FileSchema = {
    "definitions":
    {
        "NpcEntry":
        {
            "properties":
            {
                "id": { "type": "integer" },
                "name": { "type" : "string" },
                "isNPC": { "type": "boolean" },
                "race": { "type" : "integer" }
            },
            "required": [ "id", "name", "isNPC", "race" ],
            "additionalProperties": False
        }
    },

    "type": "object",
    "required": [ "npcs" ],
    "additionalProperties": False,
    "properties": 
    {
        "npcs":
        {
            "type": "array",
            "npcs": { "$ref": "#/definitions/NpcEntry" }
        }
    }
}

The JSON file and schema are processed using the jsonschema package for Python, (I am using python 3.7 on a Mac).

The method I use to read and validate is below, I have removed a lot of the general validation to make the code as short and usable as possible:

import json
import jsonschema

def _ReadJsonfile(self, filename, schemaSystem, fileType):

    with open(filename) as fileHandle:
        fileContents = fileHandle.read()
 
    jsonData = json.loads(fileContents)

    try:
        jsonschema.validate(instance=jsonData, schema=schemaSystem)

    except jsonschema.exceptions.ValidationError as ex:
        print(f"JSON schema validation failed for file '{filename}'")
        return None

    return jsonData

Upvotes: 0

Views: 6164

Answers (1)

Ether
Ether

Reputation: 53966

at: "npcs": { "$ref": "#/definitions/NpcEntry" }

change "npcs" to "items". npcs is not a valid keyword so it is ignored. The only validation that is happening is at the top level, verifying that the data is an object and that the one property is an array.

Upvotes: 4

Related Questions