Json
The Json
component offers a few JSON utilities. It uses PHP's native json_encode()
and json_decode()
.
Encoding and Decoding
The encode()
and decode()
methods will automatically throw a \JsonException
, if encoding or decoding fails. It does so by setting the JSON_THROW_ON_ERROR
bitmask option, when invoked.
use Aedart\Utils\Json;
$encoded = Json::encode([
'name' => 'Reilly',
'age' => 32
]);
// ------------------------------------------ //
$decoded = Json::decode('{"name":"Michele Rodriguez","age":4}');
Validation
You can also validate if a value is a valid JSON encoded string, using the isValid()
method.
echo Json::isValid('{ "name": "Sven" }'); // true
echo Json::isValid('{ "name": "Sven"'); // false