简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM