json
, (*1)
A json_encode/decode wrapper with specific, catchable exceptions., (*2)
Installation
composer require ksmz/json
, (*3)
Basic Usage
use ksmz\json\Json;
Json::encode(['foo' => 'bar']);
Exceptions
All exceptions extend from ksmz\json\Exceptions\JsonException
., (*4)
try {
Json::encode(...);
} catch (RecursionException $exception) {
// Specific exception
} catch (JsonException $exception) {
// All possible exceptions
}
Error codes and messages can be retrieved from the corresponding exception ($e->getMessage()
/$e->getCode()
).
Codes correspond to their respective error constants., (*5)
For messages, exceptions with use messages identical to what json_last_error_msg()
might return. Check out the php-src for examples., (*6)
Available Exceptions
public static $errors = [
JSON_ERROR_DEPTH => DepthException::class,
JSON_ERROR_STATE_MISMATCH => InvalidJsonException::class,
JSON_ERROR_CTRL_CHAR => ControlCharacterException::class,
JSON_ERROR_SYNTAX => SyntaxException::class,
JSON_ERROR_UTF8 => Utf8Exception::class,
JSON_ERROR_UTF16 => Utf16Exception::class,
JSON_ERROR_RECURSION => RecursionException::class,
JSON_ERROR_INF_OR_NAN => InfOrNanException::class,
JSON_ERROR_UNSUPPORTED_TYPE => UnsupportedTypeException::class,
JSON_ERROR_INVALID_PROPERTY_NAME => InvalidPropertyNameException::class,
];
Some exceptions are self explantory, and some are a little vague. Check out the tests for some examples. All exception tests use the same "inputs" as what PHP internally uses to test ext-json., (*7)