Convert Figma logo to code with AI

jsonrainbow logojson-schema

PHP implementation of JSON schema. Fork of the http://jsonschemaphpv.sourceforge.net/ project

3,522
349
3,522
32

Top Related Projects

13,715

The fastest JSON schema Validator. Supports JSON Schema draft-04/06/07/2019-09/2020-12 and JSON Type Definition (RFC8927)

The JSON Schema specification

JSON Schema validation

1,169

Tiny Validator for JSON Schema v4

Quick Overview

JSON Rainbow is a JSON Schema validator and generator library for Python. It provides tools to validate JSON data against schemas, as well as generate sample JSON data based on given schemas. The library aims to simplify working with JSON Schemas in Python applications.

Pros

  • Easy-to-use API for JSON Schema validation and generation
  • Supports the latest JSON Schema specification (Draft 2020-12)
  • Includes a CLI tool for quick schema validation and data generation
  • Extensible architecture allowing custom validators and generators

Cons

  • Limited documentation and examples available
  • Smaller community compared to some other JSON Schema libraries
  • May have performance limitations with very large schemas or datasets
  • Not as feature-rich as some more established JSON Schema libraries

Code Examples

Validating JSON data against a schema:

from jsonrainbow import JSONValidator

schema = {
    "type": "object",
    "properties": {
        "name": {"type": "string"},
        "age": {"type": "integer", "minimum": 0}
    },
    "required": ["name", "age"]
}

data = {"name": "John Doe", "age": 30}

validator = JSONValidator(schema)
is_valid = validator.validate(data)
print(f"Is valid: {is_valid}")

Generating sample JSON data from a schema:

from jsonrainbow import JSONGenerator

schema = {
    "type": "array",
    "items": {
        "type": "object",
        "properties": {
            "id": {"type": "integer"},
            "title": {"type": "string"}
        },
        "required": ["id", "title"]
    },
    "minItems": 2,
    "maxItems": 5
}

generator = JSONGenerator(schema)
sample_data = generator.generate()
print(sample_data)

Using the CLI tool for schema validation:

jsonrainbow validate schema.json data.json

Getting Started

To get started with JSON Rainbow, first install it using pip:

pip install jsonrainbow

Then, you can use it in your Python code:

from jsonrainbow import JSONValidator, JSONGenerator

# Create a schema
schema = {
    "type": "object",
    "properties": {
        "name": {"type": "string"},
        "age": {"type": "integer", "minimum": 0}
    },
    "required": ["name"]
}

# Validate data
validator = JSONValidator(schema)
is_valid = validator.validate({"name": "Alice", "age": 25})
print(f"Is valid: {is_valid}")

# Generate sample data
generator = JSONGenerator(schema)
sample_data = generator.generate()
print(f"Sample data: {sample_data}")

This example demonstrates basic usage of JSON Rainbow for both validation and data generation.

Competitor Comparisons

13,715

The fastest JSON schema Validator. Supports JSON Schema draft-04/06/07/2019-09/2020-12 and JSON Type Definition (RFC8927)

Pros of Ajv

  • Significantly faster performance for large-scale validation
  • More comprehensive support for JSON Schema drafts and custom keywords
  • Extensive ecosystem with plugins and integrations

Cons of Ajv

  • Steeper learning curve due to more advanced features
  • Larger bundle size, which may impact client-side applications
  • More complex configuration for advanced use cases

Code Comparison

json-schema:

const schema = {
  type: 'object',
  properties: {
    name: { type: 'string' },
    age: { type: 'number' }
  }
};
const validator = new Validator(schema);
const isValid = validator.validate({ name: 'John', age: 30 });

Ajv:

const Ajv = require('ajv');
const ajv = new Ajv();
const schema = {
  type: 'object',
  properties: {
    name: { type: 'string' },
    age: { type: 'number' }
  }
};
const validate = ajv.compile(schema);
const isValid = validate({ name: 'John', age: 30 });

Both libraries provide JSON Schema validation, but Ajv offers more advanced features and better performance for complex schemas. json-schema has a simpler API and may be easier to use for basic validation tasks. Ajv is more suitable for large-scale applications with complex validation requirements, while json-schema might be preferable for smaller projects or when simplicity is a priority.

The JSON Schema specification

Pros of json-schema-spec

  • Official JSON Schema specification repository
  • Comprehensive documentation and examples
  • Active community involvement and regular updates

Cons of json-schema-spec

  • More complex and verbose implementation
  • Steeper learning curve for beginners
  • Potentially overwhelming for simple use cases

Code Comparison

json-schema-spec:

{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "type": "object",
  "properties": {
    "name": { "type": "string" },
    "age": { "type": "integer", "minimum": 0 }
  },
  "required": ["name"]
}

json-schema:

{
  "name": "string",
  "age": "number"
}

The json-schema-spec example provides a more detailed and feature-rich schema definition, including validation rules and metadata. In contrast, the json-schema example offers a simpler, more concise representation of the data structure, which may be sufficient for basic use cases but lacks advanced validation capabilities.

While json-schema-spec is the official and more comprehensive option, json-schema might be preferred for quick prototyping or simpler projects where extensive validation is not required. The choice between the two depends on the specific needs of the project and the desired level of schema complexity.

JSON Schema validation

Pros of jsonschema

  • More actively maintained with recent updates
  • Supports a wider range of JSON Schema versions (up to draft-07)
  • Includes additional features like custom validators and error reporting

Cons of jsonschema

  • Larger package size and potentially higher memory footprint
  • May have a steeper learning curve due to more advanced features
  • Slightly more complex API for basic validation tasks

Code Comparison

jsonschema:

const Validator = require('jsonschema').Validator;
const v = new Validator();
const instance = 4;
const schema = {"type": "number"};
console.log(v.validate(instance, schema));

json-schema:

const validate = require('json-schema').validate;
const instance = 4;
const schema = {"type": "number"};
console.log(validate(instance, schema));

Summary

While jsonschema offers more features and active development, json-schema provides a simpler API for basic validation tasks. jsonschema is better suited for complex validation scenarios and projects requiring support for newer JSON Schema drafts. json-schema might be preferable for simpler use cases or projects with stricter size constraints. The choice between the two depends on the specific requirements of your project, such as the need for advanced features, schema version support, and simplicity of implementation.

1,169

Tiny Validator for JSON Schema v4

Pros of tv4

  • Lightweight and fast JSON Schema validator
  • Supports draft-04 of JSON Schema
  • Extensive test suite ensuring reliability

Cons of tv4

  • Limited support for newer JSON Schema drafts
  • Less active maintenance compared to json-schema
  • Fewer advanced features and customization options

Code Comparison

tv4:

var valid = tv4.validate(data, schema);
if (valid) {
    console.log('Valid!');
} else {
    console.log(tv4.error);
}

json-schema:

const Ajv = require("ajv")
const ajv = new Ajv()
const validate = ajv.compile(schema)
const valid = validate(data)
if (!valid) console.log(validate.errors)

Key Differences

  • tv4 is more straightforward to use with a simpler API
  • json-schema (using Ajv) offers more advanced features and better performance
  • json-schema has better support for recent JSON Schema drafts
  • tv4 has a smaller footprint and may be suitable for simpler projects
  • json-schema is more actively maintained and has a larger community

Use Cases

tv4 is ideal for:

  • Quick validation tasks
  • Projects with simple schema requirements
  • Environments where a small footprint is crucial

json-schema is better for:

  • Complex validation scenarios
  • Projects requiring support for latest JSON Schema drafts
  • Applications needing high performance and extensive customization

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

JSON Schema for PHP

Build Status Latest Stable Version Total Downloads

A PHP Implementation for validating JSON Structures against a given Schema with support for Schemas of Draft-3 or Draft-4. 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.

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: features of Drafts newer than Draft-4 might not be supported!

Basic usage

<?php

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

// 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:

<?php

use JsonSchema\SchemaStorage;
use JsonSchema\Validator;
use JsonSchema\Constraints\Factory;
use JsonSchema\Constraints\Constraint;

$request = (object)[
    'processRefund'=>"true",
    'refundAmount'=>"17"
];

$validator->validate(
    $request, (object) [
    "type"=>"object",
        "properties"=>(object)[
            "processRefund"=>(object)[
                "type"=>"boolean"
            ],
            "refundAmount"=>(object)[
                "type"=>"number"
            ]
        ]
    ],
    Constraint::CHECK_MODE_COERCE_TYPES
); // validates!

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

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

<?php

use JsonSchema\SchemaStorage;
use JsonSchema\Validator;
use JsonSchema\Constraints\Factory;

$jsonSchema = <<<'JSON'
{
    "type": "object",
    "properties": {
        "data": {
            "oneOf": [
                { "$ref": "#/definitions/integerData" },
                { "$ref": "#/definitions/stringData" }
            ]
        }
    },
    "required": ["data"],
    "definitions": {
        "integerData" : {
            "type": "integer",
            "minimum" : 0
        },
        "stringData" : {
            "type": "string"
        }
    }
}
JSON;

// Schema must be decoded before it can be used for validation
$jsonSchemaObject = json_decode($jsonSchema);

// The SchemaStorage can resolve references, loading additional schemas from file as needed, etc.
$schemaStorage = new SchemaStorage();

// This does two things:
// 1) Mutates $jsonSchemaObject to normalize the references (to file://mySchema#/definitions/integerData, etc)
// 2) Tells $schemaStorage that references to file://mySchema... should be resolved by looking in $jsonSchemaObject
$schemaStorage->addSchema('file://mySchema', $jsonSchemaObject);

// Provide $schemaStorage to the Validator so that references can be resolved during validation
$jsonValidator = new Validator(new Factory($schemaStorage));

// JSON must be decoded before it can be validated
$jsonToValidateObject = json_decode('{"data":123}');

// Do validation (use isValid() and getErrors() to check the result)
$jsonValidator->validate($jsonToValidateObject, $jsonSchemaObject);

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.

FlagDescription
Constraint::CHECK_MODE_NORMALValidate in 'normal' mode - this is the default
Constraint::CHECK_MODE_TYPE_CASTEnable fuzzy type checking for associative arrays and objects
Constraint::CHECK_MODE_COERCE_TYPESConvert data types to match the schema where possible
Constraint::CHECK_MODE_EARLY_COERCEApply type coercion as soon as possible
Constraint::CHECK_MODE_APPLY_DEFAULTSApply default values from the schema if not set
Constraint::CHECK_MODE_ONLY_REQUIRED_DEFAULTSWhen applying defaults, only set values that are required
Constraint::CHECK_MODE_EXCEPTIONSThrow an exception immediately if validation fails
Constraint::CHECK_MODE_DISABLE_FORMATDo not validate "format" constraints
Constraint::CHECK_MODE_VALIDATE_SCHEMAValidate the schema as well as the provided document

Please note that using CHECK_MODE_COERCE_TYPES or CHECK_MODE_APPLY_DEFAULTS will modify your original data.

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.

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