Skip to content

JSON Schema

Greg Bowler edited this page Mar 1, 2025 · 3 revisions

Validating JSON data against a schema ensures that the structure and types of the data match predefined expectations. This helps catch errors early, enforce consistency, and maintain data integrity when handling JSON-based APIs.

The Validator class provides schema validation for any JsonObject. It checks JSON data against a provided JSON Schema and returns a ValidationResult of either an instance of ValidationSuccess or ValidationError.

Validating a JSON Object

To validate a JsonObject, instantiate a Validator with a schema and call validate() with the JSON data:

$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) {
	echo "Error validating JSON!", PHP_EOL;

	foreach($result->getErrorList() as $propertyName => $errorString) {
		echo "$propertyName: $errorString", PHP_EOL;
	}
}
else {
	echo "Everything is OK!", PHP_EOL;
}

Validation Results

  • ValidationSuccess: Returned when the JSON data conforms to the schema.
  • ValidationError: Contains an error list explaining why the JSON does not match the schema.

Example Validation Error Output

Error validating JSON!
/: The property colr is not defined and the definition does not allow additional properties
/colour: The property colour is required
/food/2: Integer value found, but a string is required

Run the above example from the repository.

Why Use JSON Schema Validation?

  • Early error detection – Prevents malformed data from being processed.
  • Automatic enforcement – Ensures JSON adheres to a predefined structure.
  • Improved maintainability – Clearly defines expected data formats.