json-schema-spec
json-schema-spec copied to clipboard
better support for decimals encoded as strings
A common way to represent decimals in JSON is to serialize them as a string. This side-steps the floating point precision issues during transport and validation, such as mentioned by #312. Eventually a deserializer can then transform the string into a language-specific decimal type such as the Python Decimal.
See for instance DecimalField in Django REST Framework
http://www.django-rest-framework.org/api-guide/fields/#decimalfield
or the Marshmallow serialization library:
https://marshmallow.readthedocs.io/en/latest/api_reference.html#marshmallow.fields.Decimal
which includes extra notes on how to handle such precision issues.
This case isn't very well supported by JSON-Schema. multipleOf is insufficient as there are no guarantees around the representation of number in JSON.
You can define a pattern with a regex that restricts string input to decimals, but the implementer needs to create this regex, the error messages aren't very pretty, it's hard to restrict the input by a total amount of digits, and it's not possible to use minimum or maximum.
Should JSON Schema support this use case? Similar to how you have "number" and "integer" dealing with the same underlying JSON type, we could we have a "decimal" type that validates strings specifically and allows the minimum & maximum logic. It would make the implementation of validators more complex in languages that don't have a decimal/fixed point type, but it does seem to be a common use case.
(I myself ran into it when writing code that converts a Django REST Framework serializer DecimalField into a JSON schema representation but it's not really possible to support max_digits or min_value/max_value).