PHPackages                             ropi/json-schema-evaluator - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Validation &amp; Sanitization](/categories/validation)
4. /
5. ropi/json-schema-evaluator

ActiveLibrary[Validation &amp; Sanitization](/categories/validation)

ropi/json-schema-evaluator
==========================

JSON Schema Evaluator

v0.4.3(1y ago)1220MITPHPPHP &gt;=8.1.0

Since Aug 4Pushed 1y ago1 watchersCompare

[ Source](https://github.com/ro-pi/json-schema-evaluator)[ Packagist](https://packagist.org/packages/ropi/json-schema-evaluator)[ Docs](https://www.robertpiplica.de)[ RSS](/packages/ropi-json-schema-evaluator/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (10)Dependencies (4)Versions (14)Used By (0)

A modern JSON Schema evaluator for PHP
======================================

[](#a-modern-json-schema-evaluator-for-php)

This library is a PHP based implementation for evaluating and validating [JSON Schemas](https://json-schema.org/). The library can be easily extended with your own keywords and drafts.

Requirements
------------

[](#requirements)

- PHP &gt;= 8.1
- ext-bcmath
- ext-mbstring
- ext-fileinfo

Table of contents
-----------------

[](#table-of-contents)

- [Installation](#installation)
- [Supported drafts](#supported-drafts)
- [Basic examples](#basic-examples)
    - [Basic usage](#basic-usage)
    - [Read individual error results](#read-individual-error-results)
    - [Formatting results](#formatting-results)
- [Mutations](#mutations)
    - [Default values](#default-values)
    - [Content decoding](#content-decoding)
- [Advanced examples](#advanced-examples)
    - [Assert content media type](#assert-content-media-type)
    - [Assert format](#assert-format)
    - [Short-circuiting](#short-circuiting)
    - [Big numbers](#big-numbers-interpret-numeric-strings-as-numbers)
    - [Custom keywords](#custom-keywords)

Installation
------------

[](#installation)

The library can be installed from a command line interface by using [composer](https://getcomposer.org/).

Supported drafts
----------------

[](#supported-drafts)

### Draft 2020-12 ([Core](https://json-schema.org/draft/2020-12/json-schema-core.html) and [Validation](https://json-schema.org/draft/2020-12/json-schema-validation.html))

[](#draft-2020-12-core-and-validation)

Passes all tests of [official JSON schema test suite](https://github.com/json-schema-org/JSON-Schema-Test-Suite) except the following optional tests:

- [optional/refOfUnknownKeyword.json](https://github.com/json-schema-org/JSON-Schema-Test-Suite/blob/master/tests/draft2020-12/optional/refOfUnknownKeyword.json): This means that you cannot use the **$ref** keyword to reference schemas that are located inside unknown keywords.
- [optional/ecmascript-regex.json](https://github.com/json-schema-org/JSON-Schema-Test-Suite/blob/master/tests/draft2020-12/optional/ecmascript-regex.json): This means that the specifics of Ecmascript regular expressions are not respected. Instead, regular expressions are evaluated as PERL regular expressions.

```
composer require ropi/json-schema-evaluator

```

Basic examples
--------------

[](#basic-examples)

### Basic usage

[](#basic-usage)

```
$schema = json_decode('{
    "type": "string",
    "maxLength": 5
}');

$evaluator = new \Ropi\JsonSchemaEvaluator\JsonSchemaEvaluator();

// Each JSON Schema must be statically analyzed once.
$staticEvaluationContext = $evaluator->evaluateStatic($schema, new \Ropi\JsonSchemaEvaluator\EvaluationConfig\StaticEvaluationConfig(
    defaultDraft: new \Ropi\JsonSchemaEvaluator\Draft\Draft202012()
));

$instance1 = "hello";
$evaluator->evaluate($instance1, $staticEvaluationContext); // Returns true

$instance2 = "helloworld";
$evaluator->evaluate($instance2, $staticEvaluationContext); // Returns false
```

### Read individual error results

[](#read-individual-error-results)

```
$valid = $evaluator->evaluate(
    instance: $instance2,
    staticEvaluationContext: $staticEvaluationContext,
    results: $results
);

foreach ($results as $result) {
    /** @var $result \Ropi\JsonSchemaEvaluator\EvaluationContext\RuntimeEvaluationResult */
    if ($result->type === 'error') {
        echo "Error keyword location: '{$result->keywordLocation}'\n";
        echo "Error instance location: '{$result->instanceLocation}'\n";
        echo "Error message: {$result->error}\n";
    }
}
```

Output of above example:

```
Error keyword location: '/maxLength'
Error instance location: ''
Error message: At most 5 characters are allowed, but there are 10.

```

### Formatting results

[](#formatting-results)

In the following example, the results are formatted as [Basic Output Structure](https://json-schema.org/draft/2020-12/json-schema-core#name-basic). In addition, only the [Flag Output Structure](https://json-schema.org/draft/2020-12/json-schema-core#name-flag) is also currently supported.

```
$formattedResults = (new \Ropi\JsonSchemaEvaluator\Output\BasicOutput($valid, $results))->format();
echo json_encode($formattedResults, JSON_PRETTY_PRINT);
```

Output of above example:

```
{
  "valid": false,
  "errors": [
    {
      "type": "annotation",
      "valid": true,
      "keywordLocation": "\/type",
      "instanceLocation": "",
      "keywordName": "type",
      "error": "",
      "errorMeta": null,
      "annotation": [
        "string"
      ]
    },
    {
      "type": "error",
      "valid": false,
      "keywordLocation": "\/maxLength",
      "instanceLocation": "",
      "keywordName": "maxLength",
      "error": "At most 5 characters are allowed, but there are 10.",
      "errorMeta": null
    }
  ]
}
```

Mutations
---------

[](#mutations)

### Default values

[](#default-values)

If a default value is defined with the [default keyword](https://json-schema.org/draft/2020-12/json-schema-validation#name-default), it can be automatically applied during evaluation.

```
$schema = json_decode('{
    "type": "object",
    "required": ["lastname"],
    "properties": {
        "firstname": {
            "default": "n/a"
        }
    }
}');

$evaluator = new \Ropi\JsonSchemaEvaluator\JsonSchemaEvaluator();

$staticEvaluationContext = $evaluator->evaluateStatic($schema, new \Ropi\JsonSchemaEvaluator\EvaluationConfig\StaticEvaluationConfig(
    defaultDraft: new \Ropi\JsonSchemaEvaluator\Draft\Draft202012(
        evaluateMutations: true
    )
));

$instance = (object) [
    'lastname' => 'Gauss'
];

$evaluator->evaluate($instance, $staticEvaluationContext);

echo $instance->firstname; // Prints "n/a"
```

### Content decoding

[](#content-decoding)

If encoded content is defined with the [contentEncoding keyword](https://json-schema.org/draft/2020-12/json-schema-validation#name-contentencoding), it can be automatically decoded during evaluation.

```
$schema = json_decode('{
    "contentMediaType": "application/json",
    "contentEncoding": "base64"
}');

$evaluator = new \Ropi\JsonSchemaEvaluator\JsonSchemaEvaluator();

$staticEvaluationContext = $evaluator->evaluateStatic($schema, new \Ropi\JsonSchemaEvaluator\EvaluationConfig\StaticEvaluationConfig(
    defaultDraft: new \Ropi\JsonSchemaEvaluator\Draft\Draft202012(
        evaluateMutations: true
    )
));

$instance = 'eyJmb28iOiAiYmFyIn0K'; // Base64 encoded JSON '{"foo": "bar"}'

$evaluator->evaluate($instance, $staticEvaluationContext); // Returns true

echo $instance; // Prints '{"foo": "bar"}'
```

Advanced examples
-----------------

[](#advanced-examples)

### Assert content media type

[](#assert-content-media-type)

If content media type is defined with the [contentMediaType keyword](https://json-schema.org/draft/2020-12/json-schema-validation#name-contentmediatype), it can be respected during evaluation.

```
$schema = json_decode('{
    "contentMediaType": "application/json"
}');

$evaluator = new \Ropi\JsonSchemaEvaluator\JsonSchemaEvaluator();

$staticEvaluationContext = $evaluator->evaluateStatic($schema, new \Ropi\JsonSchemaEvaluator\EvaluationConfig\StaticEvaluationConfig(
    defaultDraft: new \Ropi\JsonSchemaEvaluator\Draft\Draft202012(
        assertContentMediaTypeEncoding: true
    )
));

$instance = '{"foo": "bar"}';
$evaluator->evaluate($instance, $staticEvaluationContext); // Returns true

$instance2 = 'invalidJSON';
$evaluator->evaluate($instance2, $staticEvaluationContext); // Returns false
```

### Assert format

[](#assert-format)

If format is defined with the [format keyword](https://json-schema.org/draft/2020-12/json-schema-validation#name-format-annotation-vocabular), it can be respected during evaluation.

```
$schema = json_decode('{
    "format": "email"
}');

$evaluator = new \Ropi\JsonSchemaEvaluator\JsonSchemaEvaluator();

$staticEvaluationContext = $evaluator->evaluateStatic($schema, new \Ropi\JsonSchemaEvaluator\EvaluationConfig\StaticEvaluationConfig(
    defaultDraft: new \Ropi\JsonSchemaEvaluator\Draft\Draft202012(
        assertFormat: true
    )
));

$instance = 'test@example.com';
$evaluator->evaluate($instance, $staticEvaluationContext, $runtimeEvaluationConfig); // Returns true

$instance2 = 'invalidEmail';
$evaluator->evaluate($instance2, $staticEvaluationContext, $runtimeEvaluationConfig); // Returns false
```

### Short-circuiting

[](#short-circuiting)

By default, all keywords are evaluated, even if the first keyword validation fails. If short circuiting is activated, the evaluation stops at the first negative validation result.

```
$config = new \Ropi\JsonSchemaEvaluator\EvaluationConfig\StaticEvaluationConfig(
    defaultDraft: new \Ropi\JsonSchemaEvaluator\Draft\Draft202012(
        shortCircuit: true
    )
);
```

### Big numbers (interpret numeric strings as numbers)

[](#big-numbers-interpret-numeric-strings-as-numbers)

```
$schema = json_decode('{
    "type": "integer"
}');

$evaluator = new \Ropi\JsonSchemaEvaluator\JsonSchemaEvaluator();

$staticEvaluationContext = $evaluator->evaluateStatic($schema, new \Ropi\JsonSchemaEvaluator\EvaluationConfig\StaticEvaluationConfig(
    defaultDraft: new \Ropi\JsonSchemaEvaluator\Draft\Draft202012(
        acceptNumericStrings: true
    )
));

$instance = json_decode('6565650699413464649797946464646464649797979', false, 512, JSON_BIGINT_AS_STRING);
$evaluator->evaluate($instance, $staticEvaluationContext); // Returns true
```

### Custom keywords

[](#custom-keywords)

It is possible to add custom keywords to a draft.
The following example shows how to implement a keyword where the instance must match a specific md5 hash.

```
$schema = json_decode('{
    "md5Hash": "098f6bcd4621d373cade4e832627b4f6"
}');

class Md5HashKeyword extends \Ropi\JsonSchemaEvaluator\Keyword\AbstractKeyword implements \Ropi\JsonSchemaEvaluator\Keyword\RuntimeKeywordInterface
{
    public function getName() : string
    {
        return "md5Hash";
    }

    public function evaluate(mixed $keywordValue, \Ropi\JsonSchemaEvaluator\EvaluationContext\RuntimeEvaluationContext $context): ?\Ropi\JsonSchemaEvaluator\EvaluationContext\RuntimeEvaluationResult
    {
        $instance = $context->getCurrentInstance();
        if (!is_string($instance)) {
            // Ignore keyword, because instance is not a string
            return null;
        }

        $result = $context->createResultForKeyword($this, $keywordValue);

        if (md5($instance) !== $keywordValue) {
            $result->invalidate('MD5 hash of "' . $instance . '" does not match ' . $keywordValue);
        }

        return $result;
    }
}

$draft = new \Ropi\JsonSchemaEvaluator\Draft\Draft202012();
$draft->registerKeyword(new Md5HashKeyword(), 'https://example.tld/draft/2022-03/vocab/md5'); // Register keyword with custom vocabulary

$evaluator = new \Ropi\JsonSchemaEvaluator\JsonSchemaEvaluator();

$staticEvaluationContext = $evaluator->evaluateStatic($schema, new \Ropi\JsonSchemaEvaluator\EvaluationConfig\StaticEvaluationConfig(
    defaultDraft: $draft
));

$instance = 'test';
$evaluator->evaluate($instance, $staticEvaluationContext); // Returns true, because md5 hash matches

$instance = 'hello';
$evaluator->evaluate($instance, $staticEvaluationContext); // Returns false, because md5 hash does not match
```

###  Health Score

31

—

LowBetter than 68% of packages

Maintenance33

Infrequent updates — may be unmaintained

Popularity14

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity57

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 85.5% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~90 days

Recently: every ~53 days

Total

13

Last Release

664d ago

PHP version history (2 changes)v0.1.2PHP &gt;=8.0.0

v0.2.0PHP &gt;=8.1.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/cd410511aaf1a75d11806f92a140ad8263bf46909be393cae9d4cdf4aabf8e4f?d=identicon)[ro-pi](/maintainers/ro-pi)

---

Top Contributors

[![ro-pi](https://avatars.githubusercontent.com/u/83430041?v=4)](https://github.com/ro-pi "ro-pi (71 commits)")[![RobPipe](https://avatars.githubusercontent.com/u/16306036?v=4)](https://github.com/RobPipe "RobPipe (12 commits)")

---

Tags

jsonjson-schemajson-schema-validationjson-schema-validatorphpjsonschemavalidatorevaluator

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Type Coverage Yes

### Embed Badge

![Health badge](/badges/ropi-json-schema-evaluator/health.svg)

```
[![Health](https://phpackages.com/badges/ropi-json-schema-evaluator/health.svg)](https://phpackages.com/packages/ropi-json-schema-evaluator)
```

###  Alternatives

[respect/validation

The most awesome validation engine ever created for PHP

5.9k37.4M383](/packages/respect-validation)[opis/json-schema

Json Schema Validator for PHP

64236.9M186](/packages/opis-json-schema)[seld/jsonlint

JSON Linter

1.3k217.8M205](/packages/seld-jsonlint)[ergebnis/json-schema-validator

Provides a JSON schema validator, building on top of justinrainbow/json-schema.

3626.9M7](/packages/ergebnis-json-schema-validator)[geraintluff/jsv4

A (coercive) JSON Schema v4 Validator for PHP

115455.2k4](/packages/geraintluff-jsv4)[johnstevenson/json-works

Create, edit, query and validate json

272.5M6](/packages/johnstevenson-json-works)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
