Latest release: 1.0.2
A robust wrapper for json_encode()
/json_decode()
that normalizes their
behavior across PHP versions, throws meaningful exceptions and supports schema
validation by default.
Use Composer to install the package:
$ composer require webmozart/json
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
}
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
}
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
}
Contributions to the package are always welcome!
- Report any bugs or issues you find on the issue tracker.
- You can grab the source code at the package's Git repository.
If you are having problems, send a mail to [email protected] or shout out to @webmozart on Twitter.
All contents of this package are licensed under the MIT license.