camspiers/json-pretty
Pretty-print JSON in PHP 5.3. camspiers/json-pretty provides a simple JsonPretty class with a prettify() method to format arrays/JSON into readable, indented output. Install via Composer and use in a few lines.
Installation:
Add to composer.json:
"require": {
"camspiers/json-pretty": "1.0.*"
}
Run composer update.
First Use Case: Pretty-print a Laravel response or debug variable:
use Camspiers\JsonPretty\JsonPretty;
$jsonPretty = new JsonPretty();
$prettyJson = $jsonPretty->prettify(['key' => 'value']);
dd($prettyJson); // Debug with formatted JSON
Where to Look First:
Debugging API Responses:
Replace dd($response->json()) with:
dd((new JsonPretty())->prettify($response->json()));
Logging Formatted JSON:
Log::debug('Request Data', [
'formatted_data' => (new JsonPretty())->prettify($request->all())
]);
Customizing Indentation: Extend the class (see Gotchas) to modify indentation (default: 4 spaces).
Integration with Laravel HTTP Responses:
return response()->json(
(new JsonPretty())->prettify($data),
200,
['Content-Type' => 'application/json']
);
Command-Line Pretty-Printing:
$json = file_get_contents('data.json');
echo (new JsonPretty())->prettify(json_decode($json, true));
local environments or debug contexts.JsonPretty object for multiple calls (stateless).json_encode: For complex objects, encode first:
$jsonPretty->prettify(json_encode($object));
PHP 5.3 Dependency:
json_encode flags. Workaround:
$jsonPretty->prettify(json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
Non-Array Inputs:
if (!is_array($data)) {
$data = (array) $data;
}
Special Characters:
json_encode if needed.Performance:
JSON_PRETTY_PRINT:
echo json_encode($data, JSON_PRETTY_PRINT);
$jsonPretty->prettify([
'nested' => ['array', 'with', ['deep', 'keys']],
'unicode' => 'café',
'null' => null,
'bool' => true
]);
Custom Indentation: Override the class to change spacing:
class CustomJsonPretty extends JsonPretty {
protected $indent = 2; // Use tabs or custom string
}
Add Line Breaks:
Modify the prettify method to force line breaks after keys:
$jsonPretty->prettify($data, true); // Hypothetical flag
Integration with Laravel: Create a helper:
if (!function_exists('pretty_json')) {
function pretty_json($data) {
return (new JsonPretty())->prettify($data);
}
}
Usage: pretty_json($this->data) in Blade or controllers.
AppServiceProvider if reused often:
$this->app->singleton(JsonPretty::class, function () {
return new JsonPretty();
});
How can I help you explore Laravel packages today?