Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decimal precision in JSON Schema

I want to have my JSON Schema validate that no more than two decimal places are sent to my REST api.

From what I can see in the latest JSON Schema RFC (v4) doesn't allow this. V1 had a maxDecimals validator.

Does anyone know why that was taken out?

I have a field that only holds two decimals when I store it in the database, and I do not just want to round down to two decimals. That would be changing the input quite dramatically for some users. So I want to reject any greater precision and force them to round them selves.

I can of course do this using a custom validator that I write myself, but I would rather not unless I absolutely have to.

Is there another way of indicating this in v4?

Thanks

like image 971
Jay Pete Avatar asked Dec 02 '14 22:12

Jay Pete


People also ask

Can JSON have decimal values?

JSON does not have distinct types for integers and floating-point values. Therefore, the presence or absence of a decimal point is not enough to distinguish between integers and non-integers. For example, 1 and 1.0 are two ways to represent the same value in JSON.

What does $id mean in JSON?

JSON Schema Keywords and Properties $id: Defines the base URI to resolve other URI references within the schema. title: Describes the intent of the schema. description: Gives the description of the schema. type: Defines the type of data.

How are numbers represented in JSON?

JSON number syntaxA number is represented in base 10 using decimal digits. It contains an integer component that may be prefixed with an optional minus sign, which may be followed by a fraction part and/or an exponent part. Leading zeros are not allowed.

Why would you use a string in JSON to represent a decimal number?

The main reason to transfer numeric values in JSON as strings is to eliminate any loss of precision or ambiguity in transfer.


2 Answers

They replaced it with multipleOf (via v3 divisibleBy).

For 2 decimal places, just add multipleOf: 0.01.

like image 140
fiddur Avatar answered Sep 27 '22 22:09

fiddur


I would suggest { "type": "number", "multipleOf": 0.01 } rather than { "type": "integer", "multipleOf": 0.01 }.

See http://spacetelescope.github.io/understanding-json-schema/reference/numeric.html#multiples

like image 26
cristian fusi Avatar answered Sep 27 '22 20:09

cristian fusi