PHP.GT

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.

Creating a validator

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.

Validation results

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 with error, errorList and schema

A complete example

$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:

  • colr is not part of the schema
  • colour is missing
  • the last item in food is 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.