-
-
Notifications
You must be signed in to change notification settings - Fork 1
Validating JSON Schema
JSON Schema is useful when JSON needs to match a known shape before the rest of the application uses it.
In this library, the Validator class compares a JSONObject against a schema and returns either ValidationSuccess or ValidationError.
Note
WebEngine applications inherently support automatic JSON schema validations. This documentation is only necessary for setups where WebEngine is not used.
use GT\Json\JSONObjectBuilder;
use GT\Json\Schema\ValidationError;
use GT\Json\Schema\Validator;
$builder = new JSONObjectBuilder();
$schema = $builder->fromFile("schema.json");
$json = $builder->fromFile("example.json");
$validator = new Validator($schema);
$result = $validator->validate($json);
if($result instanceof ValidationError) {
foreach($result->getErrorList() as $pointer => $message) {
echo $pointer, ": ", $message, PHP_EOL;
}
}The keys in getErrorList() are JSON Pointer style paths such as /name or /food/2.
ValidationSuccess means the JSON matched the schema.
ValidationError means at least one schema rule failed. It provides:
-
getErrorList(), which returns the validation messages keyed by path -
jsonSerialize(), which returns a JSON-friendly object witherror,errorListandschema
$builder = new JSONObjectBuilder();
$jsonString = <<<JSON
{
"name": "Cody",
"colr": "orange",
"food": [
"Biscuits",
"Mushrooms",
12345
]
}
JSON;
$schemaString = <<<JSON
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "Simple object schema",
"type": "object",
"properties": {
"name": {
"type": "string",
"minLength": 1
},
"colour": {
"type": "string"
},
"food": {
"type": "array",
"items": {
"type": "string"
}
}
},
"required": [
"name",
"colour",
"food"
],
"additionalProperties": false
}
JSON;
$schema = $builder->fromJsonString($schemaString);
$json = $builder->fromJsonString($jsonString);
$validator = new Validator($schema);
$result = $validator->validate($json);In that example, validation fails because:
-
colris not part of the schema -
colouris missing - the last item in
foodis an integer, not a string
If you are already inside a WebEngine JSON endpoint, schema validation is still an explicit step. WebEngine creates the JSONDocument response model, but it does not automatically validate incoming or outgoing JSON for you.
PHP.GT/Json is a separately maintained component used by PHP.GT/WebEngine.