robotdance / php-json-schema
A library to validate a json schema.
Requires
- php: >=5.3.3
- robotdance/php-app-config: 0.0.9
- robotdance/php-i18n: 0.0.8
Requires (Dev)
- json-schema/json-schema-test-suite: 1.2.0
- phpdocumentor/phpdocumentor: ~2
- phpunit/phpunit: ^4.8.22
README
A PHP json-schema implementation for validating JSON data agains a JSON Schema definition.
Originally forked from justinrainbow/json-schema.
In addition to the original, I18n was added for the validation messages, with initial support for en-US and pt-BR. Currently the branch "add-i18n" will be kept in sync with the forked repository, and the master branch will follow its own way.
Installation
PHP-Json-Schema is available as a Composer
package, and use it also as its dependency manager.
So you will need a composer.json in your project root, requiring php-json-schema:
... "require": { "robotdance/php-json-schema": "latest stable version" } ...
So after updating your composer file, simply update composer.
$ php composer.phar update
$ composer update
The way you update with composer will depend on how you installed composer.
Usage
<?php // Get the schema and data as objects // If you use $ref or if you are unsure, resolve those references here // This modifies the $schema object $refResolver = new JsonSchema\RefResolver(new JsonSchema\Uri\UriRetriever(), new JsonSchema\Uri\UriResolver()); $schema = $refResolver->resolve('file://' . realpath('schema.json')); $data = json_decode(file_get_contents('data.json')); // Validate $validator = new JsonSchema\Validator(); $validator->check($data, $schema); 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) { echo sprintf("[%s] %s\n", $error['property'], $error['message']); } }
Running the tests
$ vendor/bin/phpunit