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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With