GithubHelp home page GithubHelp logo

networknt / json-schema-validator Goto Github PK

View Code? Open in Web Editor NEW
769.0 43.0 316.0 2.76 MB

A fast Java JSON schema validator that supports draft V4, V6, V7, V2019-09 and V2020-12

License: Apache License 2.0

Java 98.54% Python 1.46%
json-schema-validator json-schema fast java8 draft v4 jackson java v6 v7

json-schema-validator's Introduction

Stack Overflow | Google Group | Gitter Chat | Subreddit | Youtube | Documentation | Contribution Guide |

CI Maven Central codecov.io Javadocs

This is a Java implementation of the JSON Schema Core Draft v4, v6, v7, v2019-09 and v2020-12 specification for JSON schema validation. This implementation supports Customizing Meta-Schemas, Vocabularies, Keywords and Formats.

In addition, OpenAPI 3 request/response validation is supported with the use of the appropriate meta-schema. For users who want to collect information from a JSON node based on the schema, the walkers can help. The JSON parser used is the Jackson parser. As it is a key component in our light-4j microservices framework to validate request/response against OpenAPI specification for light-rest-4j and RPC schema for light-hybrid-4j at runtime, performance is the most important aspect in the design.

JSON Schema Specification compatibility

Supported spec Compliance Compliance Compliance Compliance Compliance

Information on the compatibility support for each version, including known issues, can be found in the Compatibility with JSON Schema versions document.

Since Draft 2019-09 the format keyword only generates annotations by default and does not generate assertions.

This behavior can be overridden to generate assertions by setting the setFormatAssertionsEnabled to true in SchemaValidatorsConfig or ExecutionConfig.

Upgrading to new versions

This library can contain breaking changes in minor version releases that may require code changes.

Information on notable or breaking changes when upgrading the library can be found in the Upgrading to new versions document.

The Releases page will contain information on the latest versions.

Comparing against other implementations

The JSON Schema Validation Comparison project from Creek has an informative Comparison of JVM based Schema Validation Implementations which compares both the functional and performance characteristics of a number of different Java implementations.

The Bowtie project has a report that compares functional characteristics of different implementations, including non-Java implementations, but does not do any performance benchmarking.

Why this library

Performance

This should be the fastest Java JSON Schema Validator implementation.

The following is the benchmark results from the JSON Schema Validator Perftest project that uses the Java Microbenchmark Harness.

Note that the benchmark results are highly dependent on the input data workloads and schemas used for the validation.

In this case this workload is using the Draft 4 specification and largely tests the performance of the evaluating the properties keyword. You may refer to Results of performance comparison of JVM based JSON Schema Validation Implementations for benchmark results for more typical workloads

If performance is an important consideration, the specific sample workloads should be benchmarked, as there are different performance characteristics when certain keywords are used. For instance the use of the unevaluatedProperties or unevaluatedItems keyword will trigger annotation collection in the related validators, such as the properties or items validators, and annotation collection will adversely affect performance.

NetworkNT 1.3.1
Benchmark                                                          Mode  Cnt       Score      Error   Units
NetworkntBenchmark.testValidate                                   thrpt   10    6776.693 ±  115.309   ops/s
NetworkntBenchmark.testValidate:·gc.alloc.rate                    thrpt   10     971.191 ±   16.420  MB/sec
NetworkntBenchmark.testValidate:·gc.alloc.rate.norm               thrpt   10  165318.816 ±    0.459    B/op
NetworkntBenchmark.testValidate:·gc.churn.G1_Eden_Space           thrpt   10     968.894 ±   51.234  MB/sec
NetworkntBenchmark.testValidate:·gc.churn.G1_Eden_Space.norm      thrpt   10  164933.962 ± 8636.203    B/op
NetworkntBenchmark.testValidate:·gc.churn.G1_Survivor_Space       thrpt   10       0.002 ±    0.001  MB/sec
NetworkntBenchmark.testValidate:·gc.churn.G1_Survivor_Space.norm  thrpt   10       0.274 ±    0.218    B/op
NetworkntBenchmark.testValidate:·gc.count                         thrpt   10      89.000             counts
NetworkntBenchmark.testValidate:·gc.time                          thrpt   10      99.000                 ms
Everit 1.14.1
Benchmark                                                          Mode  Cnt       Score       Error   Units
EveritBenchmark.testValidate                                      thrpt   10    3719.192 ±   125.592   ops/s
EveritBenchmark.testValidate:·gc.alloc.rate                       thrpt   10    1448.208 ±    74.746  MB/sec
EveritBenchmark.testValidate:·gc.alloc.rate.norm                  thrpt   10  449621.927 ±  7400.825    B/op
EveritBenchmark.testValidate:·gc.churn.G1_Eden_Space              thrpt   10    1446.397 ±    79.919  MB/sec
EveritBenchmark.testValidate:·gc.churn.G1_Eden_Space.norm         thrpt   10  449159.799 ± 18614.931    B/op
EveritBenchmark.testValidate:·gc.churn.G1_Survivor_Space          thrpt   10       0.001 ±     0.001  MB/sec
EveritBenchmark.testValidate:·gc.churn.G1_Survivor_Space.norm     thrpt   10       0.364 ±     0.391    B/op
EveritBenchmark.testValidate:·gc.count                            thrpt   10     133.000              counts
EveritBenchmark.testValidate:·gc.time                             thrpt   10     148.000                  ms

Functionality

This implementation is tested against the JSON Schema Test Suite. As tests are continually added to the suite, these test results may not be current.

Implementations Overall DRAFT_03 DRAFT_04 DRAFT_06 DRAFT_07 DRAFT_2019_09 DRAFT_2020_12
NetworkNt pass: r:4703 (100.0%) o:2369 (100.0%)
fail: r:0 (0.0%) o:1 (0.0%)
pass: r:600 (100.0%) o:251 (100.0%)
fail: r:0 (0.0%) o:0 (0.0%)
pass: r:796 (100.0%) o:318 (100.0%)
fail: r:0 (0.0%) o:0 (0.0%)
pass: r:880 (100.0%) o:541 (100.0%)
fail: r:0 (0.0%) o:0 (0.0%)
pass: r:1201 (100.0%) o:625 (100.0%)
fail: r:0 (0.0%) o:0 (0.0%)
pass: r:1226 (100.0%) o:634 (99.8%)
fail: r:0 (0.0%) o:1 (0.2%)
  • Note that this uses the ECMA 262 Validator option turned on for the pattern tests.

Jackson Parser

This library uses Jackson which is a Java JSON parser that is widely used in other projects. If you are already using the Jackson parser in your project, it is natural to choose this library over others for schema validation.

YAML Support

The library works with JSON and YAML on both schema definitions and input data.

OpenAPI Support

The OpenAPI 3.0 specification is using JSON schema to validate the request/response, but there are some differences. With a configuration file, you can enable the library to work with OpenAPI 3.0 validation.

Minimal Dependencies

Following the design principle of the Light Platform, this library has minimal dependencies to ensure there are no dependency conflicts when using it.

Required Dependencies

The following are the dependencies that will automatically be included when this library is included.

<dependency>
    <!-- Used for logging -->
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-api</artifactId>
    <version>${version.slf4j}</version>
</dependency>

<dependency>
    <!-- Used to process JSON -->
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>${version.jackson}</version>
</dependency>

<dependency>
    <!-- Used to process YAML -->
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-yaml</artifactId>
    <version>${version.jackson}</version>
</dependency>

<dependency>
    <!-- Used to validate RFC 3339 date and date-time -->
    <groupId>com.ethlo.time</groupId>
    <artifactId>itu</artifactId>
    <version>${version.itu}</version>
</dependency>
Optional Dependencies

The following are the optional dependencies that may be required for certain options.

These are not automatically included and setting the relevant option without adding the library will result in a ClassNotFoundException.

<!-- This is required when setting setEcma262Validator(true)  -->
<dependency>
    <!-- Used to validate ECMA 262 regular expressions -->
    <groupId>org.jruby.joni</groupId>
    <artifactId>joni</artifactId>
    <version>${version.joni}</version>
    <optional>true</optional>
</dependency>
Excludable Dependencies

The following are required dependencies that are automatically included, but can be explicitly excluded if they are not required.

The YAML dependency can be excluded if this is not required. Attempting to process schemas or input that are YAML will result in a ClassNotFoundException.

<dependency>
    <groupId>com.networknt</groupId>
    <artifactId>json-schema-validator</artifactId>
    <exclusions>
        <exclusion>
            <groupId>com.fasterxml.jackson.dataformat</groupId>
            <artifactId>jackson-dataformat-yaml</artifactId>
        </exclusion>
    </exclusions>
</dependency>

The Ethlo Time dependency can be excluded if accurate validation of the date-time format is not required. The date-time format will then use java.time.OffsetDateTime to determine if the date-time is valid .

<dependency>
    <groupId>com.networknt</groupId>
    <artifactId>json-schema-validator</artifactId>
    <exclusions>
        <exclusion>
            <groupId>com.ethlo.time</groupId>
            <artifactId>itu</artifactId>
        </exclusion>
    </exclusions>
</dependency>

Community

This library is very active with a lot of contributors. New features and bug fixes are handled quickly by the team members. Because it is an essential dependency of the light-4j framework in the same GitHub organization, it will be evolved and maintained along with the framework.

Prerequisite

The library supports Java 8 and up. If you want to build from the source code, you need to install JDK 8 locally. To support multiple version of JDK, you can use SDKMAN

Usage

Adding the dependency

This package is available on Maven central.

Maven:

<dependency>
    <groupId>com.networknt</groupId>
    <artifactId>json-schema-validator</artifactId>
    <version>1.4.0</version>
</dependency>

Gradle:

dependencies {
    implementation(group: 'com.networknt', name: 'json-schema-validator', version: '1.4.0');
}

Validating inputs against a schema

The following example demonstrates how inputs are validated against a schema. It comprises the following steps.

  • Creating a schema factory with the default schema dialect and how the schemas can be retrieved.
    • Configuring mapping the $id to a retrieval URI using schemaMappers.
    • Configuring how the schemas are loaded using the retrieval URI using schemaLoaders. For instance a Map<String, String> schemas containing a mapping of retrieval URI to schema data as a String can by configured using builder.schemaLoaders(schemaLoaders -> schemaLoaders.schemas(schemas)). This also accepts a Function<String, String> schemaRetrievalFunction.
  • Creating a configuration for controlling validator behavior.
  • Loading a schema from a schema location along with the validator configuration.
  • Using the schema to validate the data along with setting any execution specific configuration like for instance the locale or whether format assertions are enabled.
// This creates a schema factory that will use Draft 2020-12 as the default if $schema is not specified
// in the schema data. If $schema is specified in the schema data then that schema dialect will be used
// instead and this version is ignored.
JsonSchemaFactory jsonSchemaFactory = JsonSchemaFactory.getInstance(VersionFlag.V202012, builder -> 
    // This creates a mapping from $id which starts with https://www.example.org/ to the retrieval URI classpath:schema/
    builder.schemaMappers(schemaMappers -> schemaMappers.mapPrefix("https://www.example.org/", "classpath:schema/"))
);

SchemaValidatorsConfig config = new SchemaValidatorsConfig();
// By default JSON Path is used for reporting the instance location and evaluation path
config.setPathType(PathType.JSON_POINTER);
// By default the JDK regular expression implementation which is not ECMA 262 compliant is used
// Note that setting this to true requires including the optional joni dependency
// config.setEcma262Validator(true);

// Due to the mapping the schema will be retrieved from the classpath at classpath:schema/example-main.json.
// If the schema data does not specify an $id the absolute IRI of the schema location will be used as the $id.
JsonSchema schema = jsonSchemaFactory.getSchema(SchemaLocation.of("https://www.example.org/example-main.json"), config);
String input = "{\r\n"
    + "  \"main\": {\r\n"
    + "    \"common\": {\r\n"
    + "      \"field\": \"invalidfield\"\r\n"
    + "    }\r\n"
    + "  }\r\n"
    + "}";

Set<ValidationMessage> assertions = schema.validate(input, InputFormat.JSON, executionContext -> {
    // By default since Draft 2019-09 the format keyword only generates annotations and not assertions
    executionContext.getExecutionConfig().setFormatAssertionsEnabled(true);
});

Validating a schema against a meta-schema

The following example demonstrates how a schema is validated against a meta-schema.

This is actually the same as validating inputs against a schema except in this case the input is the schema and the schema used is the meta-schema.

Note that the meta-schemas for Draft 4, Draft 6, Draft 7, Draft 2019-09 and Draft 2020-12 are bundled with the library and these classpath resources will be used by default.

JsonSchemaFactory jsonSchemaFactory = JsonSchemaFactory.getInstance(VersionFlag.V202012);

SchemaValidatorsConfig config = new SchemaValidatorsConfig();
// By default JSON Path is used for reporting the instance location and evaluation path
config.setPathType(PathType.JSON_POINTER);
// By default the JDK regular expression implementation which is not ECMA 262 compliant is used
// Note that setting this to true requires including the optional joni dependency
// config.setEcma262Validator(true);

// Due to the mapping the meta-schema will be retrieved from the classpath at classpath:draft/2020-12/schema.
JsonSchema schema = jsonSchemaFactory.getSchema(SchemaLocation.of(SchemaId.V202012), config);
String input = "{\r\n"
    + "  \"type\": \"object\",\r\n"
    + "  \"properties\": {\r\n"
    + "    \"key\": {\r\n"
    + "      \"title\" : \"My key\",\r\n"
    + "      \"type\": \"invalidtype\"\r\n"
    + "    }\r\n"
    + "  }\r\n"
    + "}";
Set<ValidationMessage> assertions = schema.validate(input, InputFormat.JSON, executionContext -> {
    // By default since Draft 2019-09 the format keyword only generates annotations and not assertions
    executionContext.getConfig().setFormatAssertionsEnabled(true);
});

Results and output formats

Results

The following types of results are generated by the library.

Type Description
Assertions Validation errors generated by a keyword on a particular input data instance. This is generally described in a ValidationMessage or in a OutputUnit. Note that since Draft 2019-09 the format keyword no longer generates assertions by default and instead generates only annotations unless configured otherwise using a configuration option or by using a meta-schema that uses the appropriate vocabulary.
Annotations Additional information generated by a keyword for a particular input data instance. This is generally described in a OutputUnit. Annotation collection and reporting is turned off by default. Annotations required by keywords such as unevaluatedProperties or unevaluatedItems are always collected for evaluation purposes and cannot be disabled but will not be reported unless configured to do so.

The following information is used to describe both types of results.

Type Description
Evaluation Path This is the set of keys from the root through which evaluation passes to reach the schema for evaluating the instance. This includes $ref and $dynamicRef. eg. /properties/bar/$ref/properties/bar-prop
Schema Location This is the canonical IRI of the schema plus the JSON pointer fragment to the schema that was used for evaluating the instance. eg. https://json-schema.org/schemas/example#/$defs/bar/properties/bar-prop
Instance Location This is the JSON pointer fragment to the instance data that was being evaluated. eg. /bar/bar-prop

Assertions contains the following additional information

Type Description
Message The validation error message.
Code The error code.
Message Key The message key used for generating the message for localization.
Arguments The arguments used for generating the message.
Type The keyword that generated the message.
Property The property name that caused the validation error for example for the required keyword. Note that this is not part of the instance location as that points to the instance node.
Schema Node The JsonNode pointed to by the Schema Location.
Instance Node The JsonNode pointed to by the Instance Location.
Details Additional details that can be set by custom keyword validator implementations. This is not used by the library.

Annotations contains the following additional information

Type Description
Value The annotation value generated

Output formats

This library implements the Flag, List and Hierarchical output formats defined in the Specification for Machine-Readable Output for JSON Schema Validation and Annotation.

The List and Hierarchical output formats are particularly helpful for understanding how the system arrived at a particular result.

Output Format Description
Default Generates the list of assertions.
Boolean Returns true if the validation is successful. Note that the fail fast option is turned on by default for this output format.
Flag Returns an OutputFlag object with valid having true if the validation is successful. Note that the fail fast option is turned on by default for this output format.
List Returns an OutputUnit object with details with a list of OutputUnit objects with the assertions and annotations. Note that annotations are not collected by default and it has to be enabled as it will impact performance.
Hierarchical Returns an OutputUnit object with a hierarchy of OutputUnit objects for the evaluation path with the assertions and annotations. Note that annotations are not collected by default and it has to be enabled as it will impact performance.

The following example shows how to generate the hierarchical output format with annotation collection and reporting turned on and format assertions turned on.

JsonSchemaFactory factory = JsonSchemaFactory.getInstance(VersionFlag.V202012);
SchemaValidatorsConfig config = new SchemaValidatorsConfig();
config.setPathType(PathType.JSON_POINTER);
config.setFormatAssertionsEnabled(true);
JsonSchema schema = factory.getSchema(SchemaLocation.of("https://json-schema.org/schemas/example"), config);
        
OutputUnit outputUnit = schema.validate(inputData, InputFormat.JSON, OutputFormat.HIERARCHICAL, executionContext -> {
    executionContext.getExecutionConfig().setAnnotationCollectionEnabled(true);
    executionContext.getExecutionConfig().setAnnotationCollectionFilter(keyword -> true);
});

The following is sample output from the Hierarchical format.

{
  "valid" : false,
  "evaluationPath" : "",
  "schemaLocation" : "https://json-schema.org/schemas/example#",
  "instanceLocation" : "",
  "droppedAnnotations" : {
    "properties" : [ "foo", "bar" ],
    "title" : "root"
  },
  "details" : [ {
    "valid" : false,
    "evaluationPath" : "/properties/foo/allOf/0",
    "schemaLocation" : "https://json-schema.org/schemas/example#/properties/foo/allOf/0",
    "instanceLocation" : "/foo",
    "errors" : {
      "required" : "required property 'unspecified-prop' not found"
    }
  }, {
    "valid" : false,
    "evaluationPath" : "/properties/foo/allOf/1",
    "schemaLocation" : "https://json-schema.org/schemas/example#/properties/foo/allOf/1",
    "instanceLocation" : "/foo",
    "droppedAnnotations" : {
      "properties" : [ "foo-prop" ],
      "title" : "foo-title",
      "additionalProperties" : [ "foo-prop", "other-prop" ]
    },
    "details" : [ {
      "valid" : false,
      "evaluationPath" : "/properties/foo/allOf/1/properties/foo-prop",
      "schemaLocation" : "https://json-schema.org/schemas/example#/properties/foo/allOf/1/properties/foo-prop",
      "instanceLocation" : "/foo/foo-prop",
      "errors" : {
        "const" : "must be a constant value 1"
      },
      "droppedAnnotations" : {
        "title" : "foo-prop-title"
      }
    } ]
  }, {
    "valid" : false,
    "evaluationPath" : "/properties/bar/$ref",
    "schemaLocation" : "https://json-schema.org/schemas/example#/$defs/bar",
    "instanceLocation" : "/bar",
    "droppedAnnotations" : {
      "properties" : [ "bar-prop" ],
      "title" : "bar-title"
    },
    "details" : [ {
      "valid" : false,
      "evaluationPath" : "/properties/bar/$ref/properties/bar-prop",
      "schemaLocation" : "https://json-schema.org/schemas/example#/$defs/bar/properties/bar-prop",
      "instanceLocation" : "/bar/bar-prop",
      "errors" : {
        "minimum" : "must have a minimum value of 10"
      },
      "droppedAnnotations" : {
        "title" : "bar-prop-title"
      }
    } ]
  } ]
}

Configuration

Execution Configuration

Name Description Default Value
annotationCollectionEnabled Controls whether annotations are collected during processing. Note that collecting annotations will adversely affect performance. false
annotationCollectionFilter The predicate used to control which keyword to collect and report annotations for. This requires annotationCollectionEnabled to be true. keyword -> false
locale The locale to use for generating messages in the ValidationMessage. Note that this value is copied from SchemaValidatorsConfig for each execution. Locale.getDefault()
failFast Whether to return failure immediately when an assertion is generated. Note that this value is copied from SchemaValidatorsConfig for each execution but is automatically set to true for the Boolean and Flag output formats. false
formatAssertionsEnabled The default is to generate format assertions from Draft 4 to Draft 7 and to only generate annotations from Draft 2019-09. Setting to true or false will override the default behavior. null

Schema Validators Configuration

Name Description Default Value
pathType The path type to use for reporting the instance location and evaluation path. Set to PathType.JSON_POINTER to use JSON Pointer. PathType.DEFAULT
ecma262Validator Whether to use the ECMA 262 joni library to validate the pattern keyword. This requires the dependency to be manually added to the project or a ClassNotFoundException will be thrown. false
executionContextCustomizer This can be used to customize the ExecutionContext generated by the JsonSchema for each validation run. null
schemaIdValidator This is used to customize how the $id values are validated. Note that the default implementation allows non-empty fragments where no base IRI is specified and also allows non-absolute IRI $id values in the root schema. JsonSchemaIdValidator.DEFAULT
messageSource This is used to retrieve the locale specific messages. DefaultMessageSource.getInstance()
preloadJsonSchema Whether the schema will be preloaded before processing any input. This will use memory but the execution of the validation will be faster. true
preloadJsonSchemaRefMaxNestingDepth The max depth of the evaluation path to preload when preloading refs. 40
cacheRefs Whether the schemas loaded from refs will be cached and reused for subsequent runs. Setting this to false will affect performance but may be neccessary to prevent high memory usage for the cache if multiple nested applicators like anyOf, oneOf and allOf are used. true
locale The locale to use for generating messages in the ValidationMessage. Locale.getDefault()
failFast Whether to return failure immediately when an assertion is generated. false
formatAssertionsEnabled The default is to generate format assertions from Draft 4 to Draft 7 and to only generate annotations from Draft 2019-09. Setting to true or false will override the default behavior. null

Performance Considerations

When the library creates a schema from the schema factory, it creates a distinct validator instance for each location on the evaluation path. This means if there are different $ref that reference the same schema location, different validator instances are created for each evaluation path.

When the schema is created, the library will automatically preload all the validators needed and resolve references. At this point, no exceptions will be thrown if a reference cannot be resolved. If there are references that are cyclic, only the first cycle will be preloaded. If you wish to ensure that remote references can all be resolved, the initializeValidators method needs to be called on the JsonSchema which will throw an exception if there are references that cannot be resolved.

The JsonSchema created from the factory should be cached and reused. Not reusing the JsonSchema means that the schema data needs to be repeated parsed with validator instances created and references resolved.

Collecting annotations will adversely affect validation performance.

The earlier draft specifications contain less keywords that can potentially impact performance. For instance the use of the unevaluatedProperties or unevaluatedItems keyword will trigger annotation collection in the related validators, such as the properties or items validators.

This does not mean that using a schema with a later draft specification will automatically cause a performance impact. For instance, the properties validator will perform checks to determine if annotations need to be collected, and checks if the meta-schema contains the unevaluatedProperties keyword and whether the unevaluatedProperties keyword exists adjacent the evaluation path.

Projects

The light-rest-4j, light-graphql-4j and light-hybrid-4j use this library to validate the request and response based on the specifications. If you are using other frameworks like Spring Boot, you can use the OpenApiValidator, a generic OpenAPI 3.0 validator based on the OpenAPI 3.0 specification.

If you have a project using this library, please submit a PR to add your project below.

Contributors

Thanks to the following people who have contributed to this project. If you are using this library, please consider to be a sponsor for one of the contributors.

@stevehu

@prashanth-chaitanya

@fdutton

@valfirst

@BalloonWen

@jiachen1120

@ddobrin

@eskabetxe

@ehrmann

@prashanthjos

@Subhajitdas298

@FWiesner

@rhwood

@jawaff

@nitin1891

For all contributors, please visit https://github.com/networknt/json-schema-validator/graphs/contributors

If you are a contributor, please join the GitHub Sponsors and switch the link to your sponsors dashboard via a PR.

Sponsors

Individual Sponsors

Corporation Sponsors

json-schema-validator's People

Contributors

andreasaloew avatar anjnerajat avatar aznan2 avatar balloonwen avatar bartoszm avatar chrisken avatar costas80 avatar ddobrin avatar dependabot[bot] avatar dreis2211 avatar ehrmann avatar eskabetxe avatar fdutton avatar fwiesner avatar gavinchenyan avatar jawaff avatar jiachen1120 avatar jorgesartori avatar justin-tay avatar kosty avatar nicholasazar avatar nitin1891 avatar olegshtch avatar prashanth-chaitanya avatar prashanthjos avatar rhwood avatar stevehu avatar subhajitdas298 avatar valfirst avatar vmaurin avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

json-schema-validator's Issues

Undertow Dependency in pom.xml

Hi,

Great job. I was taking a look at the library but noticed the undertow dependency in the pom and didn't see anywhere in the code where it is being used. Also could there be some more documentations even if it is javadoc so one can tell easily and quickly what is going on where.

Thanks for this.

Add Custom message

How to add custom message for validators. below is my sample schema.

{
"$schema": "http://json-schema.org/draft-04/schema#",
"definitions": {},
"properties": {
"active": {
"type": "boolean"
},
"name": {
"type": "string",
"requiredErrorCode": "name is required"
}
},
"required": ["name"]
}

Should ValidationMessage.getArguments() be public?

I think this was just an oversight, and I'm happy to open a PR for it, but before I open the PR, I figured I'd ask.

In ValidationMessage, getArguments() has default access, but setArguments() has public access. Was this an intentional design choice, or were they just flipped by mistake?

Relevant code

support multiple json files

Does this library support multiple json files?

I'm having this schema:

{
  "$schema": "http://json-schema.org/draft-04/schema#",

  "definitions": {
    "address": {
      "type": "object",
      "properties": {
        "street_address": { "type": "string" },
        "city":           { "type": "string" },
        "state":          { "type": "string" }
      },
      "required": ["street_address", "city", "state"]
    }
  },

  "type": "object",

  "properties": {
    "billing_address": { "$ref": "file2.json#/address" },
    "shipping_address": { "$ref": "file2.json#/address" }
  }
}

and file2.json


 {
    "address": {
      "type": "object",
      "properties": {
        "street_address": { "type": "string" },
        "city":           { "type": "string" },
        "state":          { "type": "string" }
      },
      "required": ["street_address", "city", "state"]
    }
  }

and I'm getting this error:

Exception in thread "main" com.networknt.schema.JsonSchemaException: com.fasterxml.jackson.databind.JsonMappingException: No content to map due to end-of-input
 at [Source: UNKNOWN; line: 1, column: 0]
	at com.networknt.schema.JsonSchemaFactory.getSchema(JsonSchemaFactory.java:57)
	at com.networknt.schema.RefValidator.<init>(RefValidator.java:63)
	at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
	at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
	at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
	at java.lang.reflect.Constructor.newInstance(Constructor.java:408)
	at com.networknt.schema.JsonSchema.read(JsonSchema.java:120)
	at com.networknt.schema.JsonSchema.<init>(JsonSchema.java:54)
	at com.networknt.schema.PropertiesValidator.<init>(PropertiesValidator.java:36)
	at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
	at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
	at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
	at java.lang.reflect.Constructor.newInstance(Constructor.java:408)
	at com.networknt.schema.JsonSchema.read(JsonSchema.java:120)
	at com.networknt.schema.JsonSchema.<init>(JsonSchema.java:54)
	at com.networknt.schema.JsonSchema.<init>(JsonSchema.java:44)
	at com.networknt.schema.JsonSchemaFactory.getSchema(JsonSchemaFactory.java:64)
	at json.JsonTest.main(JsonTest.java:19)
Caused by: com.fasterxml.jackson.databind.JsonMappingException: No content to map due to end-of-input
 at [Source: UNKNOWN; line: 1, column: 0]
	at com.fasterxml.jackson.databind.JsonMappingException.from(JsonMappingException.java:261)
	at com.fasterxml.jackson.databind.ObjectMapper._initForReading(ObjectMapper.java:3829)
	at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:3774)
	at com.fasterxml.jackson.databind.ObjectMapper.readTree(ObjectMapper.java:2312)
	at com.networknt.schema.JsonSchemaFactory.getSchema(JsonSchemaFactory.java:53)
	... 17 more

On single json file it works. Am I doing something wrong?

Regular expression should allowed input be limited?

Hello! I went back and read the regular expression section for the JSON schema standard. It turns out that a full ECMA 262 (aka Javascript) regular expression engine is not required. The specification says that implementations SHOULD follow ECMA 262 but not that it MUST use it. The specification also recommends that "schema authors SHOULD limit themselves to the following regular expression tokens..."

One possible feature to this library is to add validation to enforce that regular expressions are limited to the tokens that are recommended in the schema. This is one way to ensure compatibility between Java regular expressions and ECMA 262 regular expressions. The recommended tokens are:

  • individual Unicode characters, as defined by the JSON specification [RFC7159];
  • simple character classes ([abc]), range character classes ([a-z]);
  • complemented character classes ([^abc], [^a-z]);
  • simple quantifiers: "+" (one or more), "" (zero or more), "?" (zero or one), and their lazy versions ("+?", "?", "??");
  • range quantifiers: "{x}" (exactly x occurrences), "{x,y}" (at least x, at most y, occurrences), {x,} (x occurrences or more), and their lazy versions;
  • the beginning-of-input ("^") and end-of-input ("$") anchors;
  • simple grouping ("(...)") and alternation ("|").

It would be a little tricky to implement the logic that only accepted the above tokens. Is it a good idea? What if someone really wants to use Java specific regular expressions? Should the library stop them?

Support for $ref external schema references?

We have a schema that refers to three other schemas using $ref. The others are at the same relative path (folder). Trying to resolve by URL. The first schema is:
https://scap.nist.gov/schema/nvd/feed/0.1/nvd_cve_feed_json_0.1_beta.schema

The others are
https://scap.nist.gov/schema/nvd/feed/0.1/cvss-v3.0.json
https://scap.nist.gov/schema/nvd/feed/0.1/cvss-v2.0.json
https://scap.nist.gov/schema/nvd/feed/0.1/CVE_JSON_4.0_min.schema

Getting warning in log:
16:27:08,402 WARN [com.networknt.schema.JsonMetaSchema] (quartzScheduler_Worker-1) Could not load validator $ref

Any tips for troubleshooting? Is $ref supported by json-schema-validator? Nice library BTW, it has saved us a lot of time.

Schema id does not declare a base URL for relative $ref URLs

When resolving relative $references, URLs are constructed using the reference value directly without using the base URL of the referencing schema.

https://spacetelescope.github.io/understanding-json-schema/structuring.html?highlight=dependencies#the-id-property

For example, if you own the foo.bar domain, and you had a schema for addresses, you may set its id as follows:

"id": "http://foo.bar/schemas/address.json"

This provides a unique identifier for the schema, as well as, in most cases, indicating where it may be downloaded. For example: { "$ref": "person.json" }

A JSON schema validation library would fetch person.json from http://foo.bar/schemas/person.json, even if address.json was loaded from the local filesystem.

Support other JSON libraries

Yes, JSON in Java is a mess that is not going to be fixed in Java 9. As such, projects are using different libraries.
A common pattern to workaround this is to use a JsonFactory object that exposes all the needed methods and delegate to the actual implementation (Jackson, org.json, ...). It does not add significant performance overhead while making the code portable across libraries.
An example is provided here: https://github.com/jayway/JsonPath/blob/master/json-path/src/main/java/com/jayway/jsonpath/spi/json/JsonProvider.java
It would be great to have this library follow this pattern. We are using our own JSON library, so our only choice is to fork the code and update it. Now, instead of doing that our own way, I'll be happy to implement the pattern above and contribute it back, if you wish to accept it.

.getSchema() will stack overflow on recursive definitions.

With v0.1.13

I have a schema file with an recursive object, i.e. a parent object that can have a child object with the same schema.

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "type": "object",
  "properties": {
    "parent": {
      "$ref": "#/definitions/objectDef"
    }
  }
},
"definitions": {
  "objectDef": {
    "type": "object",
    "properties": {
      "value1": {
        "type": "string"
      },
      "value2": {
        "type": "string"
      },
      "childObject": {
        "$ref": "#/definitions/objectDef"
      }
    }
  }
}

It seems to not like this, as when I attempt to call schemaFactory.getSchema(node), it errors out with a stack overflow

com.networknt.schema.JsonSchemaException: java.lang.StackOverflowError
at com.networknt.schema.JsonMetaSchema.newValidator(JsonMetaSchema.java:247)
at com.networknt.schema.ValidationContext.newValidator(ValidationContext.java:24)
at com.networknt.schema.JsonSchema.read(JsonSchema.java:116)
at com.networknt.schema.JsonSchema.<init>(JsonSchema.java:56)
at com.networknt.schema.JsonSchema.<init>(JsonSchema.java:49)
at com.networknt.schema.AnyOfValidator.<init>(AnyOfValidator.java:38)
at sun.reflect.GeneratedConstructorAccessor8.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at com.networknt.schema.ValidatorTypeCode.newValidator(ValidatorTypeCode.java:102)
...
Cause: java.lang.StackOverflowError:
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:763)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:467)
at java.net.URLClassLoader.access$100(URLClassLoader.java:73)
at java.net.URLClassLoader$1.run(URLClassLoader.java:368)
at java.net.URLClassLoader$1.run(URLClassLoader.java:362)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:361)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)

I updated to v0.1.13 today from v0.1.7, where it returned the JsonSchema object for the above schema without issue.

a+ pattern in pattern validator doesn't work

The following test case fails as Java regular express returns false. Need a workaround.
{
"description": "pattern is not anchored",
"schema": {"pattern": "a+"},
"tests": [
{
"description": "matches a substring",
"data": "xxaayy",
"valid": true
}
]
}

Cannot get the validation result with self-reference schema

Steve,

I'm trying to validate the following JSON node:

{
"data": {"xxx": 5},
"tree": {"values: "zzz"}
}

against this schema:

{
  "type": "object",
  "properties": {
    "name": { "type": "string" },
    "tree": { "$ref": "#/definitions/tree" }
  },
  "definitions": {
    "tree": {
      "type": "object",
      "properties": {
        "value": { "type": "string" },
        "branches": {
          "type": "array",
          "items": { "$ref": "#/definitions/tree" },
          "minItems": 1
        }
      },
      "required": ["value"]
    }
  }
}

The node is not valid since $tree has no member named "value" (confirmed by http://www.jsonschemavalidator.net/)
My code is like this:

        Set<ValidationMessage> errors = schema.validate(node);
        for(ValidationMessage validationMessage : errors ) {
        	System.out.println("Message : " + validationMessage);
        }       

with both node and schema created by methods XXXFromClasspath of the class BaseJsonSchemaValidatorTest (I made those methods public for this purpose)
The output is

13:18:27.422 [main] DEBUG com.networknt.schema.TypeValidator - validate( {"data":{"xxx":5},"tree":{"values":"zzz"}}, {"data":{"xxx":5},"tree":{"values":"zzz"}}, $)
13:18:27.432 [main] DEBUG c.n.schema.PropertiesValidator - validate( {"data":{"xxx":5},"tree":{"values":"zzz"}}, {"data":{"xxx":5},"tree":{"values":"zzz"}}, $)
13:20:13.264 [main] DEBUG com.networknt.schema.RefValidator - validate( {"values":"zzz"}, {"data":{"xxx":5},"tree":{"values":"zzz"}}, $.tree)
13:20:43.758 [main] DEBUG com.networknt.schema.TypeValidator - validate( {"values":"zzz"}, {"data":{"xxx":5},"tree":{"values":"zzz"}}, $.tree)
13:20:45.852 [main] DEBUG c.n.schema.PropertiesValidator - validate( {"values":"zzz"}, {"data":{"xxx":5},"tree":{"values":"zzz"}}, $.tree)

No error is detected!!
Did I do something wrong?
I tried to follow with a debugger. My understanding is that the error is detected but at some point one of the stacked validate() invocations generate a null message (I'm not sure at all!).

Support Custom Validators

I need to extend the standard JSON Schema definition and add a new constraint. Would it be possible to extend the JsonSchema class to accept custom validators. This could be additional packages to search, a list of classes or of classnames?

Performance is getting worse between 0.1.11 and 0.1.12

I did another performance test with json-schema-validator-perftest by upgrade to 0.1.15 from 0.1.9 and see performance dropped significantly in percentage. Our customers are using this library in production runtime to do schema validation and we have to find out why and get it fixed. I tried to bump version one by one from 0.1.9 and found the changes in between 0.1.11 and 0.1.12 introduced some overhead. I am wondering if someone can help to figure out where is the root cause and get it fixed. Thanks.

0.1.11

Iteration 0 (in 5 ms)
Iteration 20 (in 34 ms)
Iteration 40 (in 51 ms)
Iteration 60 (in 66 ms)
Iteration 80 (in 82 ms)
Iteration 100 (in 100 ms)
Iteration 120 (in 118 ms)
Iteration 140 (in 136 ms)
Iteration 160 (in 152 ms)
Iteration 180 (in 169 ms)
Iteration 200 (in 185 ms)
Iteration 220 (in 198 ms)
Iteration 240 (in 207 ms)
Iteration 260 (in 220 ms)
Iteration 280 (in 226 ms)
Iteration 300 (in 232 ms)
Iteration 320 (in 237 ms)
Iteration 340 (in 242 ms)
Iteration 360 (in 247 ms)
Iteration 380 (in 252 ms)
Iteration 400 (in 258 ms)
Iteration 420 (in 263 ms)
Iteration 440 (in 268 ms)
Iteration 460 (in 273 ms)
Iteration 480 (in 278 ms)
END -- time in ms: 283

0.1.12

Iteration 0 (in 7 ms)
Iteration 20 (in 40 ms)
Iteration 40 (in 60 ms)
Iteration 60 (in 80 ms)
Iteration 80 (in 99 ms)
Iteration 100 (in 120 ms)
Iteration 120 (in 141 ms)
Iteration 140 (in 165 ms)
Iteration 160 (in 183 ms)
Iteration 180 (in 195 ms)
Iteration 200 (in 207 ms)
Iteration 220 (in 219 ms)
Iteration 240 (in 230 ms)
Iteration 260 (in 250 ms)
Iteration 280 (in 259 ms)
Iteration 300 (in 267 ms)
Iteration 320 (in 275 ms)
Iteration 340 (in 283 ms)
Iteration 360 (in 291 ms)
Iteration 380 (in 299 ms)
Iteration 400 (in 307 ms)
Iteration 420 (in 315 ms)
Iteration 440 (in 323 ms)
Iteration 460 (in 331 ms)
Iteration 480 (in 338 ms)
END -- time in ms: 346

#/tilda~0field, #/slash~1field, #/percent%25field don't work in reference

This test case failed, and I know other libraries handle this well. Need time to investigate but not my high priority as I don't write schema like this.

    {
        "description": "escaped pointer ref",
        "schema": {
            "tilda~field": {"type": "integer"},
            "slash/field": {"type": "integer"},
            "percent%field": {"type": "integer"},
            "properties": {
                "tilda": {"$ref": "#/tilda~0field"},
                "slash": {"$ref": "#/slash~1field"},
                "percent": {"$ref": "#/percent%25field"}
            }
        },
        "tests": [
            {
                "description": "slash invalid",
                "data": {"slash": "aoeu"},
                "valid": false
            },
            {
                "description": "tilda invalid",
                "data": {"tilda": "aoeu"},
                "valid": false
            },
            {
                "description": "percent invalid",
                "data": {"percent": "aoeu"},
                "valid": false
            },
            {
                "description": "slash valid",
                "data": {"slash": 123},
                "valid": true
            },
            {
                "description": "tilda valid",
                "data": {"tilda": 123},
                "valid": true
            },
            {
                "description": "percent valid",
                "data": {"percent": 123},
                "valid": true
            }
        ]
    },

enhance day validation regex for date format

“inputDate”: “2017-13-25",
error is
{ “error” : {“statusCode”:400,“code”:“ERR11004",“message”:“VALIDATOR_SCHEMA”,“description”:“Schema Validation Error - $.inputDate: does not match the date pattern ^\d{4}-(?:0[0-9]{1}|1[0-2]{1})-[0-9]{2}$“} }

so, months validation is correct

for days we have this
“inputDate”: “2017-12-35",
java.time.format.DateTimeParseException: Text ‘2017-12-35’ could not be parsed: Invalid value for DayOfMonth (valid values 1 - 28/31): 35
this is thrown in API code
so swagger allows invalid day
doesn’t allow invalid month

It should have similar validation error as incorrect month

Warning when validating a schema

I am using this library to validate a service's JSON outputs and one of the outputs are the JSON schema (against which everything is validated) themselves.

When validating the schema, I get this warning:

WARN  - Unknown keyword exclusiveMinimum - you should define your own Meta Schema. If the keyword is irrelevant for validation, just use a NonValidationKeyword [main] com.networknt.schema.JsonMetaSchema.newValidator()

The only place I see exclusiveMinimum is in the JSON Schema (Draft 4) itself. What is the best way to avoid this warning, since I am not using it anywhere in my own schemas?

Get errors when in json has more data

I want to get error when in json has data which doesn't have in schema for example I have schema like this:

{
  "type": "object",
  "id": "urn:jsonschema:com:xxx:xxx:Student",
  "properties": {
    "name": {
      "type": "string"
    }
  }
}

and json:

{
  "name": "Smith",
  "lastName": "Smithyan"
}

When I give the json to validate I want to get error that the "lastName" isn't defined in json schema.

Coverage ?

Hi @stevehu ,
I am interested by using your project.
Can you give me more information about the current status of this project ?
What is working, not working, known issues, missing features ...
Thanks,

Paul

java.lang.NoClassDefFoundError: Failed resolution of: Ljava/util/Optional;

Doesn't work with Android Version 6.0.1.
I am using library version com.networknt:json-schema-validator:0.1.18. Is there something that can be done ?

04-07 11:28:10.932 3799-3813/? I/TestRunner: java.lang.NoClassDefFoundError: Failed resolution of: Ljava/util/Optional;
        at com.networknt.schema.JsonMetaSchema.newValidator(JsonMetaSchema.java:241)
        at com.networknt.schema.ValidationContext.newValidator(ValidationContext.java:24)
        at com.networknt.schema.JsonSchema.read(JsonSchema.java:116)
        at com.networknt.schema.JsonSchema.<init>(JsonSchema.java:56)
        at com.networknt.schema.JsonSchema.<init>(JsonSchema.java:49)
        at com.networknt.schema.JsonSchema.<init>(JsonSchema.java:44)
        at com.networknt.schema.JsonSchemaFactory.newJsonSchema(JsonSchemaFactory.java:144)
        at com.networknt.schema.JsonSchemaFactory.getSchema(JsonSchemaFactory.java:165)

Simple, non-array dependencies don't work

It looks like only full schemas and arrays of properties are supported. Single property dependencies don't validate correctly.

Doesn't work:

{
    "dependencies": {
        "a": "b",
    }
}

Works:

{
    "dependencies": {
        "a": ["b"],
    }
}

Use of "id" field does not work for field reference

I am using a schema to define all the common fields of my objects.
But when I refer to them from some field, the validation does not work correctly, even if it puts erroneous data always comes out that is valid.

subschema with fields defenition
{
"$schema": "http://json-schema.org/draft-04/schema#",
"someSubschemaField": {
"type": "integer",
"minimum": 1,
"maximum": 99999
}
}

schema that uses subschema
{
"$schema": "http://json-schema.org/draft-04/schema#",
"id": "https://www.example.com/subschema.json",
"type": "object",
"properties": {
"someSchemaField": {
"$ref": "#/someSubschemaField"
}
}

using http://www.jsonschemavalidator.net/
validates the schema correctly

Question: is the JsonSchema class thread safe?

We are using the library in a web service to validate incoming requests against a schema. The application is by nature multi-threaded so there may be multiple validations going at the same time.

Is the JsonSchema class and the validate() method thread safe? Can I create and cache/share one instance of the JsonSchema and have all requests use it, or should I instantiate a new JsonSchema for each request?

build JAR with OSGi support

It'd be great to build the JAR so its MANIFEST becomes OSGi-compatible.
In case of building with Maven it's done just by adding a build plugin:

<plugin>
    <groupId>org.apache.felix</groupId>
    <artifactId>maven-bundle-plugin</artifactId>
    <extensions>true</extensions>
</plugin>

and by specifying the packaging:

<packaging>bundle</packaging>

Make the API more extensible

I am trying to use this library, and have run into the following design issues:

  • JsonSchemaFactory is a non-final class, but its only constructor is private
    • please make the constructor protected
  • JsonSchema is a non-final class, but its useful constructors are all package private
    • make the constructors protected
    • extract an interface so consumers can customize behavior
  • JsonSchemaFactory.Builder requires an instance of JsonSchemaFactory to instantiate - it seems silly to need to create an instance of a factory to create the builder of a new factory just to throw away the first initial factory.

In general, this library is great, but ultimately is unusable except for exactly how it was programmed. A little bit of extenisbility would go a long way.

build error on Windows environment

build 0.1.17 on windows environment and got error:

Tests in error:
JsonSchemaTest.testLoadingWithId:111 » FileNotFound http://localhost:1234/self...

It looks like Undertow server wasn't started correctly to serve the schema.
The Undertow server should be up and running and listen to 1234.

Switch to Jsoniter from Jackson?

In my other projects, I am gradually moving away from Jackson to Jsoniter due to huge performance difference. As many people are using this library with Jackson, I am wondering if we should support both or just discard Jackson as Jsoniter is very small and not depending on anything else. What do you think? Thanks.

How remove case sensitive for JSON keys

Schema mentioned: {"name" : ...}
Passing payload : {"Name": ...}

Error showing currently :

  1. "name" is required
  2. "Name" not allow additional property

Kindly advise any option to ignore only case validation. I want to allow all case should accept(camel,mix,small) ,make in-case sensitive for JSON keys.

Root properties of a model described by a schema are always validated as required

A RequiredValidator initialized with all property names is created for the root level described by a schema. JSON schema allows for optional properties also in the root level of a described model.

sample-schema.yaml

%YAML 1.2
---
$schema: http://json-schema.org/draft-04/schema#
additionalProperties: false
description: Example.
properties:
  property1:
    type: string
  property2:
    type: string
required:
 - property1
...

sample.yaml

%YAML 1.2
---
property1: TEST
...

result

$.property2: is missing but it is required

Nested references not supported

The following schema containing a self reference:
{
"type": "object",
"properties": {
"name": { "type": "string" },
"tree": { "$ref": "#/definitions/tree" }
},
"definitions": {
"tree": {
"type": "object",
"properties": {
"value": { "type": "string" },
"branches": {
"type": "array",
"items": { "$ref": "#/definitions/tree" },
"minItems": 1
}
},
"required": ["value"]
}
}
}

makes a stack overflow from com.networknt.schema.JsonSchema.read().
Not clear to me whether nested elements are supported by the standard, but some validators such as http://jeremydorn.com/json-editor/ support it.

regards
LM

A new test case ignores no-objects added in official test suites failed in this validator

This is a brand new test case added in the official test suites and it failed as I am not ignoring non-objects. If foo object is required and you just pass in a number, I just don't understand why this can be valid. Need sometime to investigate why this is true before implement it.
[
{
"description": "required validation",
"schema": {
"properties": {
"foo": {},
"bar": {}
},
"required": ["foo"]
},
"tests": [
{
"description": "ignores non-objects",
"data": 12,
"valid": true
}
]
}
]

Validator hangs on large json data files

Hello,
I am currently working on improving our JSON validator using your library, but I had trouble with large files:
Currently, running on a JSON with a size of 86MB using the FGE library takes 43825ms, but with this library it took 242476ms.
When running on smaller files(1kb) this library had a huge advantage, especially on large quantities of small files(1952ms using this library vs 18228ms using FGE).
I was wondering whether there is any configuration or settings that could help me with dealing with larger files, or whether this is a known issue.

Thank you,
Inbar Weiss

Correct behavior when both allOf and type are present

This might not be an issue with this validator; it might be an issue with another validator.

What's the correct behavior for this schema?

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "type": "object", "null"],
  "allOf": [{"required": ["b"]}]
}

Other validators accept both null and { "b": 0}, but I'm not sure if that's the correct behavior.

Github Quickstart section out-of-date

I'm looking for a Quickstart, and noticed the information on the Github front page is out of date.
Could the Quickstart section be updated? One apparently must now used a Builder() to begin with.
Thanks..

Unexpected character ('<' (code 60))

Hi,

I'm trying to use your lib to validate some json using this schema: https://realtime-listings.webservices.zpg.co.uk/docs/latest/schemas/listing/update.json

But I always get this error when loading schema file:

com.fasterxml.jackson.core.JsonParseException: Unexpected character ('<' (code 60)): expected a valid value (number, String, array, object, 'true', 'false' or 'null')
 at [Source: sun.net.www.protocol.http.HttpURLConnection$HttpInputStream@2d7a42eb; line: 1, column: 2]
	at com.fasterxml.jackson.core.JsonParser._constructError(JsonParser.java:1702) ~[jackson-core-2.8.4.jar:2.8.4]
	at com.fasterxml.jackson.core.base.ParserMinimalBase._reportError(ParserMinimalBase.java:558) ~[jackson-core-2.8.4.jar:2.8.4]
	at com.fasterxml.jackson.core.base.ParserMinimalBase._reportUnexpectedChar(ParserMinimalBase.java:456) ~[jackson-core-2.8.4.jar:2.8.4]
	at com.fasterxml.jackson.core.json.UTF8StreamJsonParser._handleUnexpectedValue(UTF8StreamJsonParser.java:2689) ~[jackson-core-2.8.4.jar:2.8.4]
	at com.fasterxml.jackson.core.json.UTF8StreamJsonParser._nextTokenNotInObject(UTF8StreamJsonParser.java:878) ~[jackson-core-2.8.4.jar:2.8.4]
	at com.fasterxml.jackson.core.json.UTF8StreamJsonParser.nextToken(UTF8StreamJsonParser.java:772) ~[jackson-core-2.8.4.jar:2.8.4]
	at com.fasterxml.jackson.databind.ObjectMapper._initForReading(ObjectMapper.java:3834) ~[jackson-databind-2.8.4.jar:2.8.4]
	at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:3783) ~[jackson-databind-2.8.4.jar:2.8.4]
	at com.fasterxml.jackson.databind.ObjectMapper.readTree(ObjectMapper.java:2321) ~[jackson-databind-2.8.4.jar:2.8.4]
	at com.networknt.schema.JsonSchemaFactory.getSchema(JsonSchemaFactory.java:63) [json-schema-validator-0.1.7.jar:na]
	at com.networknt.schema.BaseJsonValidator.obainSubSchemaNode(BaseJsonValidator.java:72) [json-schema-validator-0.1.7.jar:na]
	at com.networknt.schema.BaseJsonValidator.<init>(BaseJsonValidator.java:41) [json-schema-validator-0.1.7.jar:na]
	at com.networknt.schema.JsonSchema.<init>(JsonSchema.java:49) [json-schema-validator-0.1.7.jar:na]
	at com.networknt.schema.JsonSchema.<init>(JsonSchema.java:44) [json-schema-validator-0.1.7.jar:na]
	at com.networknt.schema.JsonSchemaFactory.getSchema(JsonSchemaFactory.java:44) [json-schema-validator-0.1.7.jar:na]

I even tried to sout the schema json content and looks ok.

I also tried to use https://json-schema-validator.herokuapp.com/index.jsp and the schema validates alright on Schema Syntax Validation but I get the same error if I try to use it on Instance Validation.

Any clues what's wrong with this schema file?

Thanks!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.