Skip to content

Getting started

Installing JSON Schema Using Composer

The recommended method of installing JSON Schema is using Composer, which installs the required dependencies on a per-project basis.

1composer require justinrainbow/json-schema

Validating using a schema on disk

1<?php
2 
3$data = json_decode(file_get_contents('data.json'));
4 
5// Validate
6$validator = new JsonSchema\Validator;
7$validator->validate($data, (object)['$ref' => 'file://' . realpath('schema.json')]);
8 
9if ($validator->isValid()) {
10 echo "The supplied JSON validates against the schema.\n";
11} else {
12 echo "JSON does not validate. Violations:\n";
13 foreach ($validator->getErrors() as $error) {
14 printf("[%s] %s\n", $error['property'], $error['message']);
15 }
16}

Validating using an inline schema

1<?php
2 
3use JsonSchema\Constraints\Factory;
4use JsonSchema\SchemaStorage;
5use JsonSchema\Validator;
6 
7require_once './vendor/autoload.php';
8 
9$data = json_decode(file_get_contents('data.json'));
10$jsonSchemaAsString = <<<'JSON'
11{
12 "type": "object",
13 "properties": {
14 "name": { "type": "string"},
15 "email": {"type": "string"}
16 },
17 "required": ["name","email"]
18}
19JSON;
20 
21$jsonSchema = json_decode($jsonSchemaAsString);
22$schemaStorage = new SchemaStorage();
23$schemaStorage->addSchema('internal://mySchema', $jsonSchema);
24$validator = new Validator(new Factory($schemaStorage));
25 
26$validator->validate($data, $jsonSchemaObject);
27if ($validator->isValid()) {
28 echo "The supplied JSON validates against the schema.\n";
29} else {
30 echo "JSON does not validate. Violations:\n";
31 foreach ($validator->getErrors() as $error) {
32 printf("[%s] %s\n", $error['property'], $error['message']);
33 }
34}