braincrafted/json
Object-oriented wrapper around PHP’s json_encode() and json_decode() providing simple static encode/decode methods plus exception-based error handling. Supports decoding to arrays or objects via Json::DECODE_ASSOC and Json::DECODE_OBJECT.
Installation:
composer require braincrafted/json:@stable
(Note: Replace @stable with the latest version from releases if needed.)
First Usage:
use Braincrafted\Json\Json;
// Encode
$jsonString = Json::encode(['name' => 'Frodo', 'age' => 33]);
// Decode
$data = Json::decode($jsonString);
Error Handling:
try {
$data = Json::decode('invalid-json');
} catch (JsonDecodeException $e) {
// Handle error (e.g., log or return fallback)
}
Braincrafted\Json\Json (class) and Braincrafted\Json\JsonDecodeException (exception).Json::DECODE_ASSOC (for associative arrays) and Json::DECODE_OBJECT (for stdClass objects).API Request/Response Handling:
// Encode Laravel response data
$responseData = ['status' => 'success', 'data' => $model->toArray()];
$jsonResponse = Json::encode($responseData);
// Decode API payloads
$requestData = Json::decode(request()->getContent(), Json::DECODE_ASSOC);
Configuration Management:
// Load JSON config (e.g., from storage)
$config = Json::decode(file_get_contents(storage_path('config/settings.json')));
Database or Cache Serialization:
// Store JSON in DB/cache
$serialized = Json::encode($complexObject);
cache()->put('key', $serialized, $ttl);
// Retrieve and decode
$data = Json::decode(cache()->get('key'));
Form Data Validation:
// Validate JSON input before processing
try {
$validated = Json::decode($rawInput, Json::DECODE_ASSOC);
// Proceed with validation logic
} catch (JsonDecodeException $e) {
return response()->json(['error' => 'Invalid JSON'], 400);
}
Laravel Service Provider:
Bind the Json class to the container for dependency injection:
$this->app->bind('json', function () {
return new Json();
});
Then inject via constructor:
public function __construct(private Json $json) {}
Custom JSON Handling Middleware: Decode JSON payloads in middleware for API routes:
public function handle($request, Closure $next) {
if ($request->isJson()) {
$request->merge(Json::decode($request->getContent(), Json::DECODE_ASSOC));
}
return $next($request);
}
Fallback for json_encode/json_decode:
Replace native functions in legacy code:
// Before: json_encode($data)
// After: Json::encode($data)
Deprecated Package:
spatie/array-to-json or Laravel’s built-in json_encode/json_decode with JSON_THROW_ON_ERROR (PHP 8.3+).Error Handling:
JsonDecodeException for invalid JSON, but no exception is thrown for json_encode failures. Validate output manually:
$json = Json::encode($data);
if (json_last_error() !== JSON_ERROR_NONE) {
throw new \RuntimeException('JSON encode failed');
}
Associative Arrays vs. Objects:
Json::DECODE_ASSOC returns arrays, while Json::DECODE_OBJECT returns stdClass. Be explicit to avoid type surprises:
// Avoid ambiguity
$data = Json::decode($json, Json::DECODE_ASSOC);
No Pretty-Printing:
json_encode, this package doesn’t support JSON_PRETTY_PRINT. Use PHP’s built-in function if needed:
echo json_encode($data, JSON_PRETTY_PRINT);
Check JSON Validity:
Use json_last_error_msg() to debug decode failures:
$data = Json::decode($json);
if (json_last_error() !== JSON_ERROR_NONE) {
logger()->error('JSON decode error: ' . json_last_error_msg());
}
Fallback for Missing Closing Brace: The package catches syntax errors, but log the raw input for debugging:
catch (JsonDecodeException $e) {
logger()->error("Invalid JSON: {$json}. Error: {$e->getMessage()}");
}
Custom JSON Options:
Extend the class to support additional json_encode flags:
class ExtendedJson extends Json {
public static function encode($data, int $options = 0, int $depth = 512) {
return parent::encode($data, $options | JSON_UNESCAPED_SLASHES);
}
}
Override Decode Behavior: Modify how decoded data is processed (e.g., type casting):
class CustomJson extends Json {
public static function decode($json, $assoc = false, $depth = 512, $flags = 0) {
$data = parent::decode($json, $assoc, $depth, $flags);
return is_array($data) ? array_map('strval', $data) : $data;
}
}
Integration with Laravel’s Jsonable:
Create a trait to make Eloquent models compatible:
trait Jsonable {
public function toJson() {
return Json::encode($this->toArray());
}
}
No Config File:
The package has no settings; all behavior is hardcoded. For customization, subclass Braincrafted\Json\Json.
PSR-4 Compliance: Ensure your autoloader is configured for PSR-4 (Laravel’s default since 5.5). If using older Laravel, verify the namespace resolution.
How can I help you explore Laravel packages today?