Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Json Pretty Print Laravel Package

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.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require webignition/json-pretty-print
    

    No configuration is required—just autoload the package.

  2. 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"
    }
    
  3. Where to Look First:

    • Class: JsonPrettyPrinter (core functionality).
    • Tests: tests/ for edge cases (e.g., malformed JSON, empty strings).
    • README: Minimal but covers basic usage.

Implementation Patterns

Common Workflows

  1. 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.

  2. Logging Pretty JSON:

    \Log::info('User data', [
        'pretty_json' => (new JsonPrettyPrinter())->prettyPrint($userDataJson)
    ]);
    

    Enhances readability in Laravel logs (e.g., single or daily channels).

  3. 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) {}
    
  4. 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).

Integration Tips

  • Laravel Debugbar: Use with barryvdh/laravel-debugbar to display pretty-printed JSON in the debug panel.
  • Telescope: Override TelescopeServiceProvider to pretty-print entries:
    Telescope::makeEntry($entry)->put('data', $this->printer->prettyPrint($entry->get('data')));
    
  • Artisan Commands: Pretty-print command output:
    $this->info($this->printer->prettyPrint(json_encode($data)));
    

Gotchas and Tips

Pitfalls

  1. 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));
    
  2. 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');
    }
    
  3. Performance: Avoid prettifying large JSON in loops or high-traffic routes. Cache or lazy-load if needed.

Debugging Tips

  • Verify Input: Use json_last_error() to check for syntax errors:
    json_decode($json); // Silently fails; use with `json_last_error()`
    
  • Custom Indentation: The default is 4 spaces, but you can override:
    $printer = new JsonPrettyPrinter(2); // 2-space indent
    

Extension Points

  1. 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);
        }
        // ...
    }
    
  2. 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));
    });
    
  3. 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)
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
amashukov/lnd-client-php
althinect/enum-permission
andydefer/laravel-actions
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor