yiisoft/json
Yii JSON is a lightweight PHP library for encoding/decoding JSON with sensible defaults. It throws JsonException on errors, supports JsonSerializable, DateTimeInterface and SimpleXMLElement, and includes safe HTML encoding for embedding JSON in pages.
Installation:
composer require yiisoft/json
No additional configuration is required—this is a lightweight, dependency-free package.
First Use Case:
use Yiisoft\Json\Json;
// Basic JSON encoding
$data = ['name' => 'John', 'age' => 30];
$json = Json::encode($data);
// Basic JSON decoding
$decoded = Json::decode($json);
Where to Look First:
encode(), decode(), encodeOptions(), decodeOptions()).Standard JSON Handling:
// Encode with default options (UTF-8, 32-bit float support)
$json = Json::encode(['key' => 'value']);
// Decode with type safety
$data = Json::decode($json, true); // true = associative array
Custom Encoding/Decoding:
use Yiisoft\Json\Encoder\EncoderInterface;
class CustomEncoder implements EncoderInterface {
public function encode($data): string {
return json_encode($data, JSON_PRETTY_PRINT);
}
}
$json = Json::encode($data, new CustomEncoder());
use Yiisoft\Json\Decoder\DecoderInterface;
class CustomDecoder implements DecoderInterface {
public function decode(string $json, bool $assoc = false, int $depth = 512, int $options = 0): mixed {
return json_decode($json, $assoc, $depth, JSON_THROW_ON_ERROR);
}
}
$data = Json::decode($json, true, new CustomDecoder());
Integration with Laravel:
use Yiisoft\Json\Json;
use Illuminate\Http\Response;
return new Response(Json::encode(['data' => $model]), 200, [
'Content-Type' => 'application/json',
]);
$input = Json::decode(request()->getContent(), true);
Error Handling:
try {
$data = Json::decode($malformedJson, true);
} catch (\JsonException $e) {
report($e);
return response()->json(['error' => 'Invalid JSON'], 400);
}
Default Options:
Json::encode() uses JSON_THROW_ON_ERROR by default (unlike PHP’s native json_encode). Ensure your code handles exceptions.Json::decode() defaults to JSON_THROW_ON_ERROR for decoders that support it (e.g., CustomDecoder above).Type Safety:
true as second argument) is not type-safe. Use JsonException handling for robustness:
$data = Json::decode($json, true, null, JSON_BIGINT_AS_STRING);
Performance:
Edge Cases:
json_encode with JSON_PRESERVE_ZERO). Use a library like spatie/array-to-xml or implement a custom encoder if needed.Json::encode(). Use mb_convert_encoding() if necessary.Reuse Encoders/Decoders:
$encoder = new \Yiisoft\Json\Encoder\JsonEncoder();
$decoder = new \Yiisoft\Json\Decoder\JsonDecoder();
// Reuse across requests (thread-safe)
$json = Json::encode($data, $encoder);
Laravel Service Provider: Bind the package to the container for dependency injection:
// config/app.php
'aliases' => [
'Json' => Yiisoft\Json\Json::class,
],
Then inject Json directly into controllers/services:
public function __construct(private Json $json) {}
Testing:
Json for unit tests:
$this->mock(Json::class)->shouldReceive('encode')->once()->andReturn('{}');
Extending Functionality:
$json = Json::encode($data, null, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
$json = Json::encode($data, null, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
Debugging:
JSON_PRETTY_PRINT for debugging:
$prettyJson = Json::encode($data, null, JSON_PRETTY_PRINT);
\Log::debug('Raw JSON:', ['data' => $json]);
How can I help you explore Laravel packages today?