I am trying to use JSON Schema to validate inputs to an API. The input follows a very simple schema:
{
"$schema": "https://json-schema.org/draft-07/schema",
"type": "object",
"properties": {
"some_key": {
"anyOf": [
{ "type": "integer" },
{ "type": "string", "pattern": "^(0|[1-9][0-9]*)$" }
]
}
},
"required": ["some_key"],
"additionalProperties": false
}
to match documents like:
{ "some_key": 1 }
{ "some_key": "12" }
{ "some_key": 22 }
{ "some_key": 42 }
{ "some_key": "42" }
Is there a way to specify in the schema that the strings should be converted to numbers? (and fail if it is not possible)
If it is impossible to convert the strings to numbers could I convert the numbers to strings?
The actual use case will have many more properties only some of which should be converted.
I know that JSON Schema includes some features that alter the input data (like default values), but I have not found reference to such a functionality.
If it matters this will be used in a PHP program likely with opis/json-schema library.
2
Answers
It seems you have provided the answer yourself. In the documentation of opis/json-schema there is a link to Support for casting.
That will probably do what you need.
This isn’t right. JSON Schema only validates what’s there; it doesn’t alter anything. This is probably why you haven’t found a reference to this functionality.
@Byted is correct in their comment. The conversion you want needs to be done by the host application.
Note that this will work to validate that you get an integer or a string that represents an integer, but you’re not going to be able to use other numeric validations (like
minimum
) on the strings.