networknt / json-schema-validator

A fast Java JSON schema validator that supports draft V4, V6, V7, V2019-09 and V2020-12
Apache License 2.0
836 stars 324 forks source link

Question about JSON validation: Type "object" can be null? #999

Closed shonigbaum closed 6 months ago

shonigbaum commented 6 months ago

Hello,

we validated an event against a schema and it seems that the validator allows an object to be null, also we didn't allow it to be null:

If we use the following schema:

{
    "$schema": "http://json-schema.org/draft-07/schema#",
    "type": "object",
    "properties": {
        "name": {
            "type": "object"
        }
    }
}

And validate this event against the given schema:

{
    "name": null
}

It returns a success message. Other validators (https://www.jsonschemavalidator.net) or compilers (https://github.com/santhosh-tekuri/jsonschema) we use in our code, do not allow this.

Null is only allowed if the type would look like: "type": ["object", "null"].

Is this a bug or are the other validators/compiler misinterpret the specifications? Is there some documentation about this?

Thanks in advance.

justin-tay commented 6 months ago

I cannot replicate this.

package com.networknt.schema;

import org.junit.jupiter.api.Test;

import com.networknt.schema.SpecVersion.VersionFlag;

public class Issue999Test {
    @Test
    void test() {
        String schemaData = "{\r\n"
                + "    \"$schema\": \"http://json-schema.org/draft-07/schema#\",\r\n"
                + "    \"type\": \"object\",\r\n"
                + "    \"properties\": {\r\n"
                + "        \"name\": {\r\n"
                + "            \"type\": \"object\"\r\n"
                + "        }\r\n"
                + "    }\r\n"
                + "}";
        String inputData = "{\r\n"
                + "    \"name\": null\r\n"
                + "}";
        JsonSchema schema = JsonSchemaFactory.getInstance(VersionFlag.V7).getSchema(schemaData);
        System.out.println(schema.validate(inputData, InputFormat.JSON, OutputFormat.HIERARCHICAL));
    }
}

The result is

{
  "valid" : false,
  "evaluationPath" : "$",
  "schemaLocation" : "#",
  "instanceLocation" : "$",
  "details" : [ {
    "valid" : false,
    "evaluationPath" : "$.properties.name",
    "schemaLocation" : "#/properties/name",
    "instanceLocation" : "$.name",
    "errors" : {
      "type" : "null found, object expected"
    }
  } ]
}
shonigbaum commented 6 months ago

Sorry for the issue. It was in another tool using your library. Thank you for the fast answer, @justin-tay.