Skip to content

bburnichon/json

 
 

Repository files navigation

Webmozart JSON

Build Status Build status Scrutinizer Code Quality Latest Stable Version Total Downloads Dependency Status

Latest release: 1.1.0

A robust wrapper for json_encode()/json_decode() that normalizes their behavior across PHP versions, throws meaningful exceptions and supports schema validation by default.

Installation

Use Composer to install the package:

$ composer require webmozart/json

Encoding

Use the JsonEncoder to encode data as JSON:

use Webmozart\Json\JsonEncoder;

$encoder = new JsonEncoder();

// Store JSON in string
$string = $encoder->encode($data);

// Store JSON in file
$encoder->encodeFile($data, '/path/to/file.json');

You can pass the path to a JSON schema in the last optional argument of both methods:

use Webmozart\Json\ValidationFailedException;

try {
    $string = $encoder->encode($data, '/path/to/schema.json');
} catch (ValidationFailedException $e) {
    // data did not match schema 
}

Decoding

Use the JsonDecoder to decode a JSON string/file:

use Webmozart\Json\JsonDecoder;

$decoder = new JsonDecoder();

// Read JSON string
$data = $decoder->decode($string);

// Read JSON file
$data = $decoder->decodeFile('/path/to/file.json');

Like JsonEncoder, the decoder accepts the path to a JSON schema in the last optional argument of its methods:

use Webmozart\Json\ValidationFailedException;

try {
    $data = $decoder->decodeFile('/path/to/file.json', '/path/to/schema.json');
} catch (ValidationFailedException $e) {
    // data did not match schema 
}

Validation

Sometimes it is necessary to separate the steps of encoding/decoding JSON data and validating it against a schema. In this case, you can omit the schema argument during encoding/decoding and use the JsonValidator to validate the data manually later on:

use Webmozart\Json\JsonDecoder;
use Webmozart\Json\JsonValidator;
use Webmozart\Json\ValidationFailedException;

$decoder = new JsonDecoder();
$validator = new JsonValidator();

$data = $decoder->decodeFile('/path/to/file.json');

// process $data...

$errors = $validator->validate($data, '/path/to/schema.json');

if (count($errors) > 0) {
    // data did not match schema 
}

Authors

Contribute

Contributions to the package are always welcome!

Support

If you are having problems, send a mail to bschussek@gmail.com or shout out to @webmozart on Twitter.

License

All contents of this package are licensed under the MIT license.

About

A robust JSON decoder/encoder with support for schema validation.

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • PHP 100.0%