-
-
Notifications
You must be signed in to change notification settings - Fork 1
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
.
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;
}
-
ValidationSuccess
: Returned when the JSON data conforms to the schema. -
ValidationError
: Contains an error list explaining why the JSON does not match the schema.
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.
- 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.
PHP.Gt/Json is a separately maintained component of PHP.Gt/WebEngine.