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

php-standard-library/json

php-standard-library/json provides JSON encode/decode helpers with sensible defaults and typed exceptions. Safer, clearer error handling than native json_encode/json_decode, ideal for consistent JSON handling in PHP apps and libraries.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require php-standard-library/json
    

    Add to composer.json under require if not using autoloading.

  2. First Use

    use PhpStandardLibrary\Json\Json;
    
    // Basic decode
    $data = Json::decode('{"key": "value"}');
    // Returns array by default (unlike native json_decode which returns object)
    
    // Basic encode
    $json = Json::encode(['key' => 'value']);
    // Returns string with consistent formatting
    
  3. Key Entry Points

    • Json::decode() – Wraps json_decode() with safer defaults.
    • Json::encode() – Wraps json_encode() with predictable options.
    • Json::prettyPrint() – Helper for human-readable output.

Where to Look First

  • Documentation: Check the package’s README.md for helper methods (e.g., Json::fromFile(), Json::toFile()).
  • Config: If the package supports it, inspect config/json.php for global defaults (e.g., associative_decode, pretty_print).
  • Exceptions: Review JsonException for error handling patterns.

Implementation Patterns

Core Workflows

  1. Consistent Decoding

    // Always returns arrays (avoids object/array ambiguity)
    $data = Json::decode($jsonString, [
        'associative' => true, // Default: true
        'depth' => 512,        // Custom depth limit
    ]);
    
  2. Safe Encoding

    // Encode with custom flags (e.g., JSON_UNESCAPED_SLASHES)
    $json = Json::encode($array, [
        'flags' => JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT,
        'depth' => 10,
    ]);
    
  3. File I/O Helpers

    // Read/write JSON files with automatic encoding/decoding
    $data = Json::fromFile('path/to/file.json');
    Json::toFile('path/to/file.json', $data);
    
  4. API Response Handling

    // Parse API responses with error validation
    try {
        $response = Json::decode($apiResponse);
    } catch (JsonException $e) {
        Log::error("Invalid JSON from API: " . $e->getMessage());
        throw new \RuntimeException("API response malformed");
    }
    

Integration Tips

  • Laravel Service Provider Bind the package to the container for dependency injection:

    $this->app->singleton('json', function () {
        return new \PhpStandardLibrary\Json\Json();
    });
    

    Then inject via constructor:

    public function __construct(private Json $json) {}
    
  • Form Request Validation Use the package to decode and validate JSON payloads in Laravel requests:

    public function rules()
    {
        $data = Json::decode($this->input());
        return [
            'data.key' => 'required|string',
        ];
    }
    
  • Testing Mock Json::decode()/encode() in unit tests to isolate logic:

    $this->partialMock(Json::class, ['decode'])
         ->shouldReceive('decode')
         ->once()
         ->andReturn(['test' => 'data']);
    

Gotchas and Tips

Pitfalls

  1. Associative Decoding Default

    • Native json_decode() returns stdClass for objects. This package defaults to arrays ('associative' => true). Explicitly set false if you need objects:
      Json::decode($json, ['associative' => false]);
      
  2. Depth Limits

    • The package enforces a default depth of 512 (vs. PHP’s default of 512). Override carefully to avoid stack overflows:
      Json::decode($json, ['depth' => 1000]); // Only if necessary!
      
  3. File Permissions

    • Json::toFile() may fail silently if the target directory lacks write permissions. Use file_put_contents() as a fallback or validate paths first.
  4. Circular References

    • Like native json_encode(), this package throws on circular references. Use Json::encode($data, ['flags' => JSON_THROW_ON_ERROR]) to enforce strict validation.
  5. UTF-8 Validation

    • The package assumes UTF-8 input. If working with raw bytes, pre-validate with mb_check_encoding() or use JSON_BIGINT_AS_STRING for large integers.

Debugging Tips

  • Enable Pretty Print Add 'pretty_print' => true to Json::encode() for debugging:

    Json::encode($data, ['pretty_print' => true]);
    
  • Custom Exceptions Catch JsonException to log malformed JSON:

    try {
        Json::decode($invalidJson);
    } catch (JsonException $e) {
        Log::debug("JSON decode error: " . $e->getMessage());
        Log::debug("Failed input: " . substr($invalidJson, 0, 200));
    }
    
  • Validate Output Use Json::validate() (if available) to check encoded strings:

    if (!Json::validate($jsonString)) {
        throw new \InvalidArgumentException("Invalid JSON string");
    }
    

Extension Points

  1. Custom Decoders Extend the package by creating a decorator:

    class CustomJson extends Json
    {
        public function decodeWithDefaults($json, array $defaults = [])
        {
            $data = parent::decode($json);
            return array_merge($defaults, $data);
        }
    }
    
  2. Global Configuration Override defaults via a service provider:

    Json::setDefaultOptions([
        'associative' => true,
        'flags' => JSON_UNESCAPED_UNICODE,
    ]);
    
  3. Laravel Facade Create a facade for convenience:

    // app/Facades/Json.php
    namespace App\Facades;
    
    use Illuminate\Support\Facades\Facade;
    
    class Json extends Facade
    {
        protected static function getFacadeAccessor() { return 'json'; }
    }
    

    Then use Json::decode() anywhere in Laravel.

  4. Testing Helpers Add a test trait for consistent JSON assertions:

    trait AssertsJson
    {
        protected function assertJsonEquals(array $expected, string $actual)
        {
            $this->assertEquals(
                Json::encode($expected),
                $actual,
                "JSON strings do not match"
            );
        }
    }
    
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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport