herrera-io/json
PHP library for working with JSON data: read, write, validate, and manipulate JSON structures with a simple API. Useful for encoding/decoding, handling JSON files, and keeping JSON processing consistent across your applications.
Installation:
composer require herrera-io/json
Ensure the package is auto-discoverable (Laravel 5.5+ handles this automatically).
First Use Case:
Replace raw json_decode() with the package’s validator and decoder:
use HerreraIo\Json\Facades\Json;
$jsonString = '{"name":"John","age":30}';
$data = Json::decode($jsonString); // Returns associative array
Where to Look First:
Json (for encode/decode).Json::validate() for schema-like checks.JsonException for error handling.src/ directory for core classes (Json.php, JsonValidator.php).Strict Decoding with Validation:
try {
$data = Json::decode($request->getContent(), true, 512); // 512 = max depth
// Proceed if valid
} catch (JsonException $e) {
abort(422, 'Invalid JSON: ' . $e->getMessage());
}
Custom Serialization: Override default behavior for Laravel models/collections:
Json::setEncoder(function ($data) {
return json_encode($data, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);
});
API Request Validation: Validate incoming JSON against expected structure:
$validator = new \HerreraIo\Json\JsonValidator();
if (!$validator->validate($request->getContent(), [
'required' => ['user_id', 'action'],
'user_id' => ['integer'],
'action' => ['string', 'min:3']
])) {
throw new \Exception('Invalid payload');
}
Laravel Integration:
public function rules()
{
return [
'data' => ['required', function ($attribute, $value) {
return Json::validate($value, ['type' => 'object']);
}],
];
}
public function toArray($request)
{
return Json::encode($this->resource->toArray());
}
Configuration Handling: Validate JSON configs during bootstrapping:
public function boot()
{
$config = config('app.custom_json');
Json::validate($config, ['type' => 'object']);
}
// Instead of:
$json = new \HerreraIo\Json\Json();
// Use:
$data = Json::decode($jsonString);
JsonException for malformed input:
try {
$data = Json::decode($input);
} catch (JsonException $e) {
Log::error('JSON decode failed: ' . $e->getMessage());
return response()->json(['error' => 'Invalid data'], 400);
}
$validated = array_map(function ($json) {
return Json::decode($json);
}, $jsonArray);
Validation Overhead:
{"key": null, "empty": ""}
Json::decode() without validation.Performance:
json_decode() is faster.$cacheKey = 'json_'.$hash;
$data = Cache::remember($cacheKey, 3600, function () use ($json) {
return Json::decode($json);
});
Circular References:
symfony/serializer).JSON_THROW_ON_ERROR with native functions or implement a custom encoder.Laravel-Specific Types:
Carbon, Collection) may not serialize/deserialize as expected.Json::setEncoder(function ($data) {
return json_encode($data, JSON_THROW_ON_ERROR);
});
Error Messages:
Json::setExceptionHandler(function ($e) {
throw new \Exception('Invalid JSON: ' . $e->getMessage());
});
Enable Strict Mode:
Use JSON_THROW_ON_ERROR for immediate feedback:
$data = Json::decode($json, true, 512, JSON_THROW_ON_ERROR);
Log Validation Errors:
$validator = new \HerreraIo\Json\JsonValidator();
if (!$validator->validate($json)) {
Log::error('Validation failed:', [
'errors' => $validator->getErrors(),
'json' => $json
]);
}
Compare with Native Functions: For debugging, test against PHP’s native functions:
$nativeResult = json_decode($json, true);
$packageResult = Json::decode($json);
dd($nativeResult === $packageResult);
Custom Validators:
Extend JsonValidator for domain-specific rules:
class UserJsonValidator extends \HerreraIo\Json\JsonValidator
{
public function validateUser($json)
{
return $this->validate($json, [
'required' => ['email', 'role'],
'email' => ['email'],
'role' => ['enum:admin,user']
]);
}
}
Custom Encoders/Decoders: Replace default behavior:
Json::setEncoder(function ($data) {
return json_encode($data, JSON_UNESCAPED_UNICODE);
});
Json::setDecoder(function ($json, $assoc = true, $depth = 512) {
return json_decode($json, $assoc, $depth, JSON_THROW_ON_ERROR);
});
Integration with Laravel Validation: Create a custom validation rule:
use HerreraIo\Json\Facades\Json;
class ValidJson implements Rule
{
public function passes($attribute, $value)
{
return Json::validate($value, ['type' => 'object']);
}
}
Usage:
'data' => ['required', new ValidJson],
Default Settings:
JSON_THROW_ON_ERROR by default, which may not match your error-handling strategy.Json::setExceptionHandler(function ($e) {
return json_decode($e->getMessage(), true);
});
Depth Limits:
512. Adjust for deep objects:
$data = Json::decode($json, true, 1000); // Increase depth
Associative Arrays:
Json::decode($json, true) returns associative arrays, but nested objects may still be stdClass.json_decode($json, true) for consistent behavior if needed.Request Handling:
Validate JSON in App\Http\Middleware\ValidateJson:
public function handle($request, Closure $next)
{
if ($request->isJson() && !$request->hasValidJson()) {
abort(422, 'Invalid JSON payload');
}
return $next($request);
}
API Resources:
Override toJson() for custom serialization:
public function toJson($request)
{
return Json::encode($this->resource->toArray());
}
Service Providers: Bind the package globally:
public function register()
{
$this->app->singleton('json', function () {
return new \HerreraIo\Json\Json();
});
}
How can I help you explore Laravel packages today?