php-standard-library/json
A small PHP Standard Library package for JSON encoding and decoding with typed exceptions and sensible defaults, providing predictable error handling for safer serialization in Laravel and other PHP projects.
Install the Package:
composer require php-standard-library/json
Publish Config:
php artisan vendor:publish --provider="PhpStandardLibrary\Json\JsonServiceProvider" --tag="json-config"
This creates config/json.php with sensible defaults (e.g., JSON_THROW_ON_ERROR enabled in development).
First Use Case: API Response
Replace response()->json() in a controller:
use PhpStandardLibrary\Json\Facades\Json;
public function show(User $user) {
return response()->json(Json::laravel()->encode($user->toArray()));
}
Json::laravel() – Laravel-specific entry point with config awareness.config/json.php – Centralize flags like JSON_PRETTY_PRINT or JSON_THROW_ON_ERROR.JsonException – Catches parsing errors with context (e.g., line numbers).public function handle(Request $request, Closure $next) {
$data = Json::laravel()->decode($request->getContent());
$request->merge($data); // Merge into request object
return $next($request);
}
return response()->json(
Json::laravel()->encode($data, pretty: env('APP_DEBUG'))
);
use PhpStandardLibrary\Json\Validation\JsonSchemaValidator;
$schema = file_get_contents('schemas/user.json');
Json::validate($request->json()->all(), $schema);
$validator = Validator::make($data, [
'name' => 'required|string',
'metadata' => function ($attribute, $value, $fail) {
Json::validate($value, file_get_contents('schemas/metadata.json'));
},
]);
$this->line(Json::laravel()->encode($data, pretty: true));
protected $casts = ['metadata' => 'json'];
public function getMetadataAttribute($value) {
return Json::laravel()->decode($value);
}
$this->app->bind('json.encoder', function () {
return new CustomJsonEncoder();
});
App\Http\Middleware\ValidateJson:
public function handle($request, Closure $next) {
Json::validate($request->json()->all(), $this->schema);
return $next($request);
}
Json::laravel() in PHPUnit:
$this->mock(Json::class)->shouldReceive('encode')->andReturn('{}');
Facade Migration:
Json::encode() → Json::laravel()->encode() breaks existing code.AppServiceProvider:
Json::extend('laravel', function () {
return new JsonFacade();
});
Deprecated Methods:
Json::pretty() is deprecated.Json::laravel()->encode($data, JSON_PRETTY_PRINT);
Validation Overhead:
Json::validate() slows down high-traffic APIs.config/json.php:
'validation' => [
'enabled' => env('APP_ENV') !== 'production',
],
Circular References:
json_encode fails on circular references.JSON_THROW_ON_ERROR and handle manually, or switch to Symfony Serializer.Config Overrides:
config/json.php) may conflict with per-request needs.Json::laravel()->encode($data, JSON_THROW_ON_ERROR, JSON_UNESCAPED_SLASHES);
Exception Context:
JsonException includes $e->getData() and $e->getContext() for debugging malformed JSON.App\Exceptions\Handler:
Log::error('JSON Error', [
'exception' => $e,
'data' => $e->getData(),
]);
Pretty-Printing:
JSON_PRETTY_PRINT for logs:
Log::debug(Json::laravel()->encode($data, JSON_PRETTY_PRINT));
Performance:
JSON_THROW_ON_ERROR vs. JSON_BIGINT_AS_STRING for large payloads.Custom Encoders/Decoders:
JsonEncoderInterface and bind in AppServiceProvider:
$this->app->bind('json.encoder', function () {
return new CustomEncoder();
});
Schema Validation:
JsonSchemaValidator for custom rules:
class CustomValidator extends JsonSchemaValidator {
public function validate($data, $schema) {
// Custom logic
}
}
Laravel Facade:
Json::laravel() behavior:
Json::extend('custom', function () {
return new CustomJsonService();
});
Event Listeners:
json.encoded/json.decoded events for logging/auditing:
event(new JsonEncoded($data, $encodedJson));
How can I help you explore Laravel packages today?