Baike.dev
All toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
J

json-schema

> 编程语言
Open source

JSON Schema for PHP

3.6K stars0 likes1 views
WebsiteGitHub

About

JSON Schema for PHP

JSON Schema for PHP

A PHP Implementation for validating JSON Structures against a given Schema with support for Schemas of Draft-3, Draft-4, Draft-6,Draft-7 or Draft 2019-09.

Features of newer Drafts might not be supported. See Table of All Versions of Everything to get an overview of all existing Drafts. See json-schema for more details about the JSON Schema specification

Compliance

Installation

Library

git clone https://github.com/jsonrainbow/json-schema.git

Composer

Install PHP Composer

composer require justinrainbow/json-schema

Usage

For a complete reference see Understanding JSON Schema.

Note: Not all drafts might be supported, check the Bowtie report on the current state of draft implementations.

Basic usage

<?php

$data = json_decode(file_get_contents('data.json'), false);

// Validate
$validator = new JsonSchema\Validator();
$validator->validate($data, (object)['$ref' => 'file://' . realpath('schema.json')]);

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']);
    }
}

Type coercion

If you're validating data passed to your application via HTTP, you can cast strings and booleans to the expected types defined by your schema:

…

A shorthand method is also available:

$validator->coerce($request, $schema);
// equivalent to $validator->validate($data, $schema, Constraint::CHECK_MODE_COERCE_TYPES);

Default values

If your schema contains default values, you can have these automatically applied during validation:

<?php

use JsonSchema\Validator;
use JsonSchema\Constraints\Constraint;

$request = (object)[
    'refundAmount'=>17
];

$validator = new Validator();

$validator->validate(
    $request,
    (object)[
        "type"=>"object",
        "properties"=>(object)[
            "processRefund"=>(object)[
                "type"=>"boolean",
                "default"=>true
            ]
        ]
    ],
    Constraint::CHECK_MODE_APPLY_DEFAULTS
); //validates, and sets defaults for missing properties

is_bool($request->processRefund); // true
$request->processRefund; // true

With inline references

…

Configuration Options

A number of flags are available to alter the behavior of the validator. These can be passed as the third argument to Validator::validate(), or can be provided as the third argument to Factory::__construct() if you wish to persist them across multiple validate() calls.

Flag Description Constraint::CHECK_MODE_NORMAL Validate in 'normal' mode - this is the default Constraint::CHECK_MODE_TYPE_CAST Enable fuzzy type checking for associative arrays and objects Constraint::CHECK_MODE_COERCE_TYPES [^1][^2] Convert data types to match the schema where possible Constraint::CHECK_MODE_EARLY_COERCE [^2] Apply type coercion as soon as possible Constraint::CHECK_MODE_APPLY_DEFAULTS [^1] Apply default values from the schema if not set Constraint::CHECK_MODE_ONLY_REQUIRED_DEFAULTS When applying defaults, only set values that are required Constraint::CHECK_MODE_EXCEPTIONS Throw an exception immediately if validation fails Constraint::CHECK_MODE_DISABLE_FORMAT Do not validate "format" constraints Constraint::CHECK_MODE_VALIDATE_SCHEMA Validate the schema as well as the provided document Constraint::CHECK_MODE_STRICT [^3] Validate the scheme using strict mode using the specified draft

[^1]: Please note that using CHECK_MODE_COERCE_TYPES or CHECK_MODE_APPLY_DEFAULTS will modify your original data. [^2]: CHECK_MODE_EARLY_COERCE has no effect unless used in combination with CHECK_MODE_COERCE_TYPES. If enabled, the validator will use (and coerce) the first compatible type it encounters, even if the schema defines another type that matches directly and does not require coercion. [^3]: CHECK_MODE_STRICT only can be used for Draft-6, Draft 7 or Draft 2019-09 at this point.

Running the tests

composer test                            # run all unit tests
composer testOnly TestClass              # run specific unit test class
composer testOnly TestClass::testMethod  # run specific unit test method
composer style-check                     # check code style for errors
composer style-fix                       # automatically fix code style errors

Contributors ✨

Thanks go to these wonderful people, without their effort this project wasn't possible.

Powered by

GitHub Issues· 23 open

View all on GitHub
  • #957

    Fatal error on window

    Updated Sep 16, 2026
  • #955

    `CHECK_MODE_COERCE_TYPES` flag does not coerce quoted ints to corresponding boolean

    BugPRs WelcomeGood first issueUpdated Sep 14, 2026
  • #953

    JsonSchemaTestSuiteTest silently runs zero tests since the suite added tests/v1/

    Updated Sep 13, 2026
  • #950

    UriResolver::resolve() throws on a parent-relative reference against a base with no path

    BugUpdated Sep 5, 2026
  • #949

    Schema ids are discovered in annotation data and unknown keywords

    BugUpdated Sep 5, 2026
  • #948

    UriResolver::resolve() inherits the base URI query and fragment

    BugUpdated Sep 5, 2026
  • #930

    Add OSSF scorecard support

    EnhancementUpdated Aug 5, 2026
  • #907

    Add support for `unevaluatedProperties` for more efficient useage of `allOf` schemas

    PRs Welcomedraft-2019Updated Jul 31, 2026

Highlights

  • •PHP
  • •json
  • •schema

> Tags

PHPjsonschema

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category编程语言
PricingOpen source

> Related tools

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言