Technically\Json
is a minimalistic wrapper around PHP native json_encode
and json_decode
functions,
which always throws an exception in case of an error.
- PHP 7.3+
- PHP 8.0
- Semver
- Tests
Look, if an error occurs with json_decode()
, by default, it sets the global error state
that can be retrieved with json_last_error()
and json_last_error_msg()
.
Alternatively, developers can use JSON_THROW_ON_ERROR
option to make json_decode()
throw
an exception in case of invalid input.
Proper way of using the native json_decode()
function, though many developers forget about it:
try {
$data = json_decode($input, false, 512, JSON_THROW_ON_ERROR);
} catch (JsonException $exception) {
// handle invalid input
}
Or this:
$data = \json_decode($input);
$error = \json_last_error();
if ($error !== JSON_ERROR_NONE) {
throw new \JsonException(\json_last_error_msg(), $error);
}
I believe it should be the default behavior of json_decode()
and json_encode()
to throw on errors.
We don't have to remember about it.
use function Technically\Json\json_decode;
try {
$data = json_decode($input);
} catch (JsonException $exception) {
// handle invalid input
}
Use Composer package manager to add the library to your project:
composer require technically/json
The namespaced json_encode()
and json_decode()
functions do always add JSON_THROW_ON_ERROR
flag,
but in the rest they work identically to the native functions: same arguments, same options, same result.
<?php
use JsonException;
use function Technically\Json\json_decode;
use function Technically\Json\json_encode;
// encode
echo json_encode(['name' => 'technically/json', 'type' => 'library']);
// decode with safety check exception to protected
try {
$data = json_decode('[{ invalid JSON');
} catch (JsonException $exception) {
// handle invalid data
}
All notable changes to this project will be documented in the CHANGELOG file.
- Implemented by Ivan Voskoboinyk