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
Add to composer.json under require if not using autoloading.
First Use
use PhpStandardLibrary\Json\Json;
// Basic decode
$data = Json::decode('{"key": "value"}');
// Returns array by default (unlike native json_decode which returns object)
// Basic encode
$json = Json::encode(['key' => 'value']);
// Returns string with consistent formatting
Key Entry Points
Json::decode() – Wraps json_decode() with safer defaults.Json::encode() – Wraps json_encode() with predictable options.Json::prettyPrint() – Helper for human-readable output.README.md for helper methods (e.g., Json::fromFile(), Json::toFile()).config/json.php for global defaults (e.g., associative_decode, pretty_print).JsonException for error handling patterns.Consistent Decoding
// Always returns arrays (avoids object/array ambiguity)
$data = Json::decode($jsonString, [
'associative' => true, // Default: true
'depth' => 512, // Custom depth limit
]);
Safe Encoding
// Encode with custom flags (e.g., JSON_UNESCAPED_SLASHES)
$json = Json::encode($array, [
'flags' => JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT,
'depth' => 10,
]);
File I/O Helpers
// Read/write JSON files with automatic encoding/decoding
$data = Json::fromFile('path/to/file.json');
Json::toFile('path/to/file.json', $data);
API Response Handling
// Parse API responses with error validation
try {
$response = Json::decode($apiResponse);
} catch (JsonException $e) {
Log::error("Invalid JSON from API: " . $e->getMessage());
throw new \RuntimeException("API response malformed");
}
Laravel Service Provider Bind the package to the container for dependency injection:
$this->app->singleton('json', function () {
return new \PhpStandardLibrary\Json\Json();
});
Then inject via constructor:
public function __construct(private Json $json) {}
Form Request Validation Use the package to decode and validate JSON payloads in Laravel requests:
public function rules()
{
$data = Json::decode($this->input());
return [
'data.key' => 'required|string',
];
}
Testing
Mock Json::decode()/encode() in unit tests to isolate logic:
$this->partialMock(Json::class, ['decode'])
->shouldReceive('decode')
->once()
->andReturn(['test' => 'data']);
Associative Decoding Default
json_decode() returns stdClass for objects. This package defaults to arrays ('associative' => true). Explicitly set false if you need objects:
Json::decode($json, ['associative' => false]);
Depth Limits
Json::decode($json, ['depth' => 1000]); // Only if necessary!
File Permissions
Json::toFile() may fail silently if the target directory lacks write permissions. Use file_put_contents() as a fallback or validate paths first.Circular References
json_encode(), this package throws on circular references. Use Json::encode($data, ['flags' => JSON_THROW_ON_ERROR]) to enforce strict validation.UTF-8 Validation
mb_check_encoding() or use JSON_BIGINT_AS_STRING for large integers.Enable Pretty Print
Add 'pretty_print' => true to Json::encode() for debugging:
Json::encode($data, ['pretty_print' => true]);
Custom Exceptions
Catch JsonException to log malformed JSON:
try {
Json::decode($invalidJson);
} catch (JsonException $e) {
Log::debug("JSON decode error: " . $e->getMessage());
Log::debug("Failed input: " . substr($invalidJson, 0, 200));
}
Validate Output
Use Json::validate() (if available) to check encoded strings:
if (!Json::validate($jsonString)) {
throw new \InvalidArgumentException("Invalid JSON string");
}
Custom Decoders Extend the package by creating a decorator:
class CustomJson extends Json
{
public function decodeWithDefaults($json, array $defaults = [])
{
$data = parent::decode($json);
return array_merge($defaults, $data);
}
}
Global Configuration Override defaults via a service provider:
Json::setDefaultOptions([
'associative' => true,
'flags' => JSON_UNESCAPED_UNICODE,
]);
Laravel Facade Create a facade for convenience:
// app/Facades/Json.php
namespace App\Facades;
use Illuminate\Support\Facades\Facade;
class Json extends Facade
{
protected static function getFacadeAccessor() { return 'json'; }
}
Then use Json::decode() anywhere in Laravel.
Testing Helpers Add a test trait for consistent JSON assertions:
trait AssertsJson
{
protected function assertJsonEquals(array $expected, string $actual)
{
$this->assertEquals(
Json::encode($expected),
$actual,
"JSON strings do not match"
);
}
}
How can I help you explore Laravel packages today?