php-standard-library/json
php-standard-library/json provides JSON encode/decode helpers with sensible defaults and typed exceptions. Safer, clearer error handling than native json_encode/json_decode, ideal for consistent JSON handling in PHP apps and libraries.
Installation:
composer require php-standard-library/json
For Laravel, register the service provider in config/app.php:
'providers' => [
PhpStandardLibrary\Json\JsonServiceProvider::class,
],
First Use Case:
Replace native json_encode()/json_decode() with the package’s methods:
// Encode with sensible defaults (throws on error)
$json = Json::encode(['key' => 'value']);
// Decode with strict validation
$data = Json::decode($json);
Configuration: Publish the config file:
php artisan vendor:publish --provider="PhpStandardLibrary\Json\JsonServiceProvider" --tag="config"
Customize config/json.php to set default flags (e.g., JSON_THROW_ON_ERROR, JSON_PRETTY_PRINT).
Consistent JSON Handling in Controllers:
// Laravel controller example
public function store(Request $request)
{
$validated = Json::decode($request->json(), Json::THROW_ON_ERROR);
$data = Json::encode($validated, JSON_PRETTY_PRINT);
return response()->json($data);
}
API Response Standardization: Use the package to enforce consistent JSON formatting across all responses:
// AppServiceProvider boot method
Response::macro('jsonStandard', function ($data) {
return response()->json(Json::encode($data, JSON_PRETTY_PRINT));
});
Request Validation: Validate incoming JSON payloads with schema validation:
public function rules()
{
return [
'payload' => 'required|json',
];
}
public function withValidator($validator)
{
$validator->after(function ($validator) {
$schema = file_get_contents('schemas/api.json');
Json::validate($this->payload, $schema);
});
}
CLI/Artisan Commands: Use the package for JSON formatting in CLI tools:
$data = Json::decode(file_get_contents('data.json'));
$prettyJson = Json::encode($data, JSON_PRETTY_PRINT);
file_put_contents('output.json', $prettyJson);
Testing: Standardize JSON assertions in PHPUnit tests:
public function testJsonResponse()
{
$response = $this->get('/api/data');
$data = Json::decode($response->getContent());
$this->assertArrayHasKey('key', $data);
}
Laravel Request/Response Pipeline:
FormRequest classes.JSON_PRETTY_PRINT for debugging).Database JSON Columns: Use the package for Eloquent model serialization:
protected $casts = [
'metadata' => 'json',
];
// Custom accessor/mutator
public function getMetadataAttribute($value)
{
return Json::decode($value);
}
public function setMetadataAttribute($value)
{
$this->attributes['metadata'] = Json::encode($value);
}
Event Handling: Serialize/deserialize JSON in event listeners:
public function handle(ApiRequestEvent $event)
{
$data = Json::decode($event->payload);
// Process data...
$response = Json::encode($data);
$event->setResponse($response);
}
Leverage Laravel Facades:
Use Json::laravel() for Laravel-specific features (e.g., config-driven flags):
$json = Json::laravel()->encode($data);
Custom Exceptions:
Extend Laravel’s exception handler to log JsonException:
public function register()
{
$this->reportable(function (JsonException $e) {
Log::error('JSON Error', [
'exception' => $e,
'data' => $e->getData(),
'file' => $e->getFile(),
'line' => $e->getLine(),
]);
});
}
Configuration-Driven Flags:
Centralize JSON encoding/decoding flags in config/json.php:
return [
'default_flags' => JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR,
'pretty_print' => env('APP_DEBUG', false) ? JSON_PRETTY_PRINT : 0,
];
Then use them in your code:
$flags = config('json.default_flags') | config('json.pretty_print');
$json = Json::encode($data, $flags);
Schema Validation: Integrate with Laravel’s validation pipeline:
public function rules()
{
return [
'payload' => ['required', 'json', function ($attribute, $value, $fail) {
$schema = file_get_contents('schemas/' . $this->route('schema'));
if (!Json::validate($value, $schema)->isValid()) {
$fail('The ' . $attribute . ' does not match the required schema.');
}
}],
];
}
Facade Namespace Changes:
Json::encode() → Json::laravel()->encode()).config/app.php or update all usages:
'aliases' => [
'Json' => App\Providers\JsonServiceProvider::class . '::jsonAlias',
],
Deprecated Methods:
Json::pretty() may be deprecated.// Old
$json = Json::pretty($data);
// New
$json = Json::encode($data, JSON_PRETTY_PRINT);
Validation Overhead:
Json::validate()) adds runtime overhead.if (config('json.validate.enabled')) {
Json::validate($data, $schema);
}
Dependency Conflicts:
symfony/validator or webonyx/graphql-php.composer.json for conflicts and update dependencies accordingly.Error Handling:
Json::decode() throws JsonException by default (due to JSON_THROW_ON_ERROR).try {
$data = Json::decode($json);
} catch (JsonException $e) {
return response()->json(['error' => 'Invalid JSON'], 400);
}
Log JSON Errors:
Extend Laravel’s exception handler to log detailed JsonException info:
public function report(Throwable $exception)
{
if ($exception instanceof JsonException) {
Log::error('JSON Decoding Error', [
'message' => $exception->getMessage(),
'data' => $exception->getData(),
'context' => $exception->getContext(),
]);
}
parent::report($exception);
}
Validate JSON Schema: Use the package’s validation to debug malformed JSON:
$validator = Json::validate($data, $schema);
if (!$validator->isValid()) {
dd($validator->getErrors()); // Debug validation errors
}
Check Config Values:
Ensure config/json.php is correctly published and configured:
php artisan config:clear
php artisan vendor:publish --tag=json-config --force
Test Edge Cases: Validate the package’s behavior with edge cases:
// Test recursive structures
$recursiveData = ['key' => ['nested' => &$recursiveData]];
try {
Json::encode($recursiveData);
} catch (JsonException $e) {
// Expected behavior: catch and handle
}
Custom JSON Flags: Extend the package to support custom flags or defaults:
// In a service provider
Json::extend(function ($encoder) {
$encoder->addFlag('CUSTOM_FLAG', JSON_UNESCAPED_UNICODE);
});
Schema Validation Rules: Create reusable validation rules for Laravel’s validator:
use Illuminate\Validation\Rule;
Rule::macro('jsonSchema', function ($schemaPath) {
return function ($attribute, $value, $
How can I help you explore Laravel packages today?