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 Laravel Package

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.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation: Add to composer.json:

    "require": {
        "camspiers/json-pretty": "1.0.*"
    }
    

    Run composer update.

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

    • README.md for basic usage.
    • Tests for edge cases (e.g., nested arrays, special characters).

Implementation Patterns

Common Workflows

  1. Debugging API Responses: Replace dd($response->json()) with:

    dd((new JsonPretty())->prettify($response->json()));
    
  2. Logging Formatted JSON:

    Log::debug('Request Data', [
        'formatted_data' => (new JsonPretty())->prettify($request->all())
    ]);
    
  3. Customizing Indentation: Extend the class (see Gotchas) to modify indentation (default: 4 spaces).

  4. Integration with Laravel HTTP Responses:

    return response()->json(
        (new JsonPretty())->prettify($data),
        200,
        ['Content-Type' => 'application/json']
    );
    
  5. Command-Line Pretty-Printing:

    $json = file_get_contents('data.json');
    echo (new JsonPretty())->prettify(json_decode($json, true));
    

Best Practices

  • Avoid in Production: Use only in local environments or debug contexts.
  • Cache Instances: Reuse the JsonPretty object for multiple calls (stateless).
  • Combine with json_encode: For complex objects, encode first:
    $jsonPretty->prettify(json_encode($object));
    

Gotchas and Tips

Pitfalls

  1. PHP 5.3 Dependency:

    • Fails on PHP 7+ due to deprecated json_encode flags. Workaround:
      $jsonPretty->prettify(json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
      
  2. Non-Array Inputs:

    • Throws exceptions for non-array/non-object inputs. Validate first:
      if (!is_array($data)) {
          $data = (array) $data;
      }
      
  3. Special Characters:

    • May mishandle Unicode or control characters. Pre-process with json_encode if needed.
  4. Performance:

    • Overhead for large datasets. Avoid in loops or high-traffic endpoints.

Debugging Tips

  • Check Output: Compare with native JSON_PRETTY_PRINT:
    echo json_encode($data, JSON_PRETTY_PRINT);
    
  • Test Edge Cases:
    $jsonPretty->prettify([
        'nested' => ['array', 'with', ['deep', 'keys']],
        'unicode' => 'café',
        'null' => null,
        'bool' => true
    ]);
    

Extension Points

  1. Custom Indentation: Override the class to change spacing:

    class CustomJsonPretty extends JsonPretty {
        protected $indent = 2; // Use tabs or custom string
    }
    
  2. Add Line Breaks: Modify the prettify method to force line breaks after keys:

    $jsonPretty->prettify($data, true); // Hypothetical flag
    
  3. 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.

Config Quirks

  • No Config File: All settings are hardcoded in the class. Extend to add flexibility.
  • No Laravel Service Provider: Register manually in AppServiceProvider if reused often:
    $this->app->singleton(JsonPretty::class, function () {
        return new JsonPretty();
    });
    
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
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