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

yiisoft/json

Yii JSON is a lightweight PHP library for encoding/decoding JSON with sensible defaults. It throws JsonException on errors, supports JsonSerializable, DateTimeInterface and SimpleXMLElement, and includes safe HTML encoding for embedding JSON in pages.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require yiisoft/json
    

    No additional configuration is required—this is a lightweight, dependency-free package.

  2. First Use Case:

    use Yiisoft\Json\Json;
    
    // Basic JSON encoding
    $data = ['name' => 'John', 'age' => 30];
    $json = Json::encode($data);
    
    // Basic JSON decoding
    $decoded = Json::decode($json);
    
  3. Where to Look First:

    • Class Documentation (methods like encode(), decode(), encodeOptions(), decodeOptions()).
    • Tests for edge cases (e.g., custom encoders, error handling).

Implementation Patterns

Core Workflows

  1. Standard JSON Handling:

    // Encode with default options (UTF-8, 32-bit float support)
    $json = Json::encode(['key' => 'value']);
    
    // Decode with type safety
    $data = Json::decode($json, true); // true = associative array
    
  2. Custom Encoding/Decoding:

    • Custom Encoder:
      use Yiisoft\Json\Encoder\EncoderInterface;
      
      class CustomEncoder implements EncoderInterface {
          public function encode($data): string {
              return json_encode($data, JSON_PRETTY_PRINT);
          }
      }
      
      $json = Json::encode($data, new CustomEncoder());
      
    • Custom Decoder:
      use Yiisoft\Json\Decoder\DecoderInterface;
      
      class CustomDecoder implements DecoderInterface {
          public function decode(string $json, bool $assoc = false, int $depth = 512, int $options = 0): mixed {
              return json_decode($json, $assoc, $depth, JSON_THROW_ON_ERROR);
          }
      }
      
      $data = Json::decode($json, true, new CustomDecoder());
      
  3. Integration with Laravel:

    • Response JSON:
      use Yiisoft\Json\Json;
      use Illuminate\Http\Response;
      
      return new Response(Json::encode(['data' => $model]), 200, [
          'Content-Type' => 'application/json',
      ]);
      
    • Request Parsing:
      $input = Json::decode(request()->getContent(), true);
      
  4. Error Handling:

    try {
        $data = Json::decode($malformedJson, true);
    } catch (\JsonException $e) {
        report($e);
        return response()->json(['error' => 'Invalid JSON'], 400);
    }
    

Gotchas and Tips

Pitfalls

  1. Default Options:

    • Json::encode() uses JSON_THROW_ON_ERROR by default (unlike PHP’s native json_encode). Ensure your code handles exceptions.
    • Json::decode() defaults to JSON_THROW_ON_ERROR for decoders that support it (e.g., CustomDecoder above).
  2. Type Safety:

    • Decoding to an associative array (true as second argument) is not type-safe. Use JsonException handling for robustness:
      $data = Json::decode($json, true, null, JSON_BIGINT_AS_STRING);
      
  3. Performance:

    • Avoid reinventing the wheel: Use the built-in encoder/decoder for 99% of cases. Custom implementations should only be used for niche scenarios (e.g., custom serialization).
  4. Edge Cases:

    • Circular References: This package does not handle circular references (unlike json_encode with JSON_PRESERVE_ZERO). Use a library like spatie/array-to-xml or implement a custom encoder if needed.
    • Unicode: Ensure your data is UTF-8 encoded before passing to Json::encode(). Use mb_convert_encoding() if necessary.

Tips

  1. Reuse Encoders/Decoders:

    $encoder = new \Yiisoft\Json\Encoder\JsonEncoder();
    $decoder = new \Yiisoft\Json\Decoder\JsonDecoder();
    
    // Reuse across requests (thread-safe)
    $json = Json::encode($data, $encoder);
    
  2. Laravel Service Provider: Bind the package to the container for dependency injection:

    // config/app.php
    'aliases' => [
        'Json' => Yiisoft\Json\Json::class,
    ],
    

    Then inject Json directly into controllers/services:

    public function __construct(private Json $json) {}
    
  3. Testing:

    • Mock Json for unit tests:
      $this->mock(Json::class)->shouldReceive('encode')->once()->andReturn('{}');
      
  4. Extending Functionality:

    • Custom JSON Options:
      $json = Json::encode($data, null, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
      
    • Pretty-Printing:
      $json = Json::encode($data, null, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
      
  5. Debugging:

    • Use JSON_PRETTY_PRINT for debugging:
      $prettyJson = Json::encode($data, null, JSON_PRETTY_PRINT);
      
    • Log raw JSON for complex issues:
      \Log::debug('Raw JSON:', ['data' => $json]);
      
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