Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

json schema date-time does not check correctly

I have a JSON and a JSON-schema

JSON:

{ "aaa": "4000-02-01 00:00:00" } 

JSON-schema:

{     "$schema": "http://json-schema.org/draft-04/schema",     "type": "object",     "properties": {          "aaa": {             "type": "string",             "format": "date-time"         }       }, "required": ["aaa"] } 

The JSON gets validated by the JSON-schema. However if I change the field aaa to "bla" the schema does not notice that it is not a date-time any longer.

Did I miss anything in the schema?

like image 899
JoachimR Avatar asked Nov 28 '13 10:11

JoachimR


People also ask

Is date valid type in JSON?

The problem with dates in JSON is that it does not specify date representation. To represent dates in JavaScript, JSON uses ISO 8601 string format to encode dates as a string. Dates are encoded as ISO 8601 strings and then treated just like a regular string when the JSON is serialized and deserialized.

How do I check if a JSON Schema is valid?

The simplest way to check if JSON is valid is to load the JSON into a JObject or JArray and then use the IsValid(JToken, JsonSchema) method with the JSON Schema. To get validation error messages, use the IsValid(JToken, JsonSchema, IList<String> ) or Validate(JToken, JsonSchema, ValidationEventHandler) overloads.

What is JSON Schema error?

This means that you have an error with the JSON data structure that you included in the body of your request and that it doesn't follow the format in which we expected to receive it. In order to know exactly what is wrong with your JSON data, you will need to validate it using a JSON schema.


2 Answers

Validation with "format" is optional. This is partly because schema authors are allowed to completely make up new formats, so expecting all formats to be validated is not reasonable.

Your library should (if it is decent) have a way to register custom validators for particular formats. For example, the tv4 validation library (in JavaScript) has the tv4.addFormat() method:

tv4.addFormat('date-time', function (data) {     return isValidDate(data); }); 

Once you've done this, then "format": "date-time" in the schema should validate dates correctly.

like image 44
cloudfeet Avatar answered Sep 21 '22 13:09

cloudfeet


For Python's jsonschema library, specify the format checker when calling validate:

jsonschema.validate(data, schema, format_checker=jsonschema.FormatChecker()) 

To validate a date-time format, the strict-rfc3339 package should be installed.

See Validating Formats.

like image 92
Beau Barker Avatar answered Sep 18 '22 13:09

Beau Barker