-
Notifications
You must be signed in to change notification settings - Fork 357
Validate using an inline schema
Danny van der Sluijs edited this page Feb 6, 2024
·
1 revision
This library support validating JSON documents using an inline schema.
+ No disk or network i/o required (beyond loading the PHP code)
- Can become difficult for larger schema's
<?php
use JsonSchema\Constraints\Factory;
use JsonSchema\SchemaStorage;
use JsonSchema\Validator;
require_once './vendor/autoload.php';
$data = json_decode(file_get_contents('data.json'));
$jsonSchemaAsString = <<<'JSON'
{
"type": "object",
"properties": {
"name": { "type": "string"},
"email": {"type": "string"}
},
"required": ["name","email"]
}
JSON;
$jsonSchema = json_decode($jsonSchemaAsString);
$schemaStorage = new SchemaStorage();
$schemaStorage->addSchema('internal://mySchema', $jsonSchema);
$validator = new Validator(new Factory($schemaStorage));
$validator->validate($data, $jsonSchemaObject);
if ($validator->isValid()) {
echo "The supplied JSON validates against the schema.\n";
} else {
echo "JSON does not validate. Violations:\n";
foreach ($validator->getErrors() as $error) {
printf("[%s] %s\n", $error['property'], $error['message']);
}
}