webignition/json-pretty-print
Pretty-print JSON strings with consistent, readable formatting. Includes a formatter you can embed in tools or CLIs to clean up minified or messy JSON, with sensible indentation and whitespace handling for clearer diffs, logs, and debugging output.
Installation:
composer require webignition/json-pretty-print
No configuration is required—just autoload the package.
First Use Case:
use Webignition\JsonPrettyPrint\JsonPrettyPrinter;
$uglyJson = '{"name":"John","age":30,"city":"New York"}';
$printer = new JsonPrettyPrinter();
$prettyJson = $printer->prettyPrint($uglyJson);
Output:
{
"name": "John",
"age": 30,
"city": "New York"
}
Where to Look First:
JsonPrettyPrinter (core functionality).tests/ for edge cases (e.g., malformed JSON, empty strings).API Response Formatting:
$response = $this->json(['data' => $uglyJson]);
$prettyResponse = $response->setContent(
(new JsonPrettyPrinter())->prettyPrint($response->getContent())
);
Useful for debugging API endpoints without modifying frontend logic.
Logging Pretty JSON:
\Log::info('User data', [
'pretty_json' => (new JsonPrettyPrinter())->prettyPrint($userDataJson)
]);
Enhances readability in Laravel logs (e.g., single or daily channels).
Service Provider Binding (for reusable access):
// app/Providers/AppServiceProvider.php
public function register()
{
$this->app->singleton(JsonPrettyPrinter::class);
}
Then inject via constructor:
public function __construct(private JsonPrettyPrinter $printer) {}
Middleware for Debug Routes:
// app/Http/Middleware/PrettyJson.php
public function handle($request, Closure $next)
{
$response = $next($request);
if ($response->headers->get('Content-Type') === 'application/json') {
$response->setContent(
$this->printer->prettyPrint($response->getContent())
);
}
return $response;
}
Apply to debug routes only (e.g., php artisan route:list --json).
barryvdh/laravel-debugbar to display pretty-printed JSON in the debug panel.TelescopeServiceProvider to pretty-print entries:
Telescope::makeEntry($entry)->put('data', $this->printer->prettyPrint($entry->get('data')));
$this->info($this->printer->prettyPrint(json_encode($data)));
Non-String Inputs: The method expects a string. Passing arrays/objects will throw:
$printer->prettyPrint(['key' => 'value']); // TypeError
Fix: Convert first:
$printer->prettyPrint(json_encode($array));
Malformed JSON:
Invalid JSON (e.g., '{key: "value"}') will throw JsonException. Handle gracefully:
try {
$pretty = $printer->prettyPrint($json);
} catch (\JsonException $e) {
return response($json, 500)->header('X-Error', 'Invalid JSON');
}
Performance: Avoid prettifying large JSON in loops or high-traffic routes. Cache or lazy-load if needed.
json_last_error() to check for syntax errors:
json_decode($json); // Silently fails; use with `json_last_error()`
$printer = new JsonPrettyPrinter(2); // 2-space indent
Custom Formatting: Extend the class to add features (e.g., colorized output):
class ColoredJsonPrinter extends JsonPrettyPrinter {
public function prettyPrint(string $json): string {
$pretty = parent::prettyPrint($json);
return $this->addColors($pretty);
}
// ...
}
Hook into Laravel Events:
Listen to illuminate.query or eloquent.* events to auto-pretty-print SQL/queries:
Event::listen('illuminate.query', function ($query) {
\Log::debug($this->printer->prettyPrint($query->sql));
});
Blade Directives: Create a custom Blade directive for views:
Blade::directive('prettyJson', function ($expression) {
return "<?php echo (new \\Webignition\\JsonPrettyPrint\\JsonPrettyPrinter())->prettyPrint({$expression}); ?>";
});
Usage:
@prettyJson($jsonVariable)
How can I help you explore Laravel packages today?