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

braincrafted/json

Object-oriented wrapper around PHP’s json_encode() and json_decode() providing simple static encode/decode methods plus exception-based error handling. Supports decoding to arrays or objects via Json::DECODE_ASSOC and Json::DECODE_OBJECT.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require braincrafted/json:@stable
    

    (Note: Replace @stable with the latest version from releases if needed.)

  2. First Usage:

    use Braincrafted\Json\Json;
    
    // Encode
    $jsonString = Json::encode(['name' => 'Frodo', 'age' => 33]);
    
    // Decode
    $data = Json::decode($jsonString);
    
  3. Error Handling:

    try {
        $data = Json::decode('invalid-json');
    } catch (JsonDecodeException $e) {
        // Handle error (e.g., log or return fallback)
    }
    

Where to Look First

  • Namespace: Braincrafted\Json\Json (class) and Braincrafted\Json\JsonDecodeException (exception).
  • Constants: Json::DECODE_ASSOC (for associative arrays) and Json::DECODE_OBJECT (for stdClass objects).
  • Documentation: The README is concise but covers core functionality.

Implementation Patterns

Common Workflows

  1. API Request/Response Handling:

    // Encode Laravel response data
    $responseData = ['status' => 'success', 'data' => $model->toArray()];
    $jsonResponse = Json::encode($responseData);
    
    // Decode API payloads
    $requestData = Json::decode(request()->getContent(), Json::DECODE_ASSOC);
    
  2. Configuration Management:

    // Load JSON config (e.g., from storage)
    $config = Json::decode(file_get_contents(storage_path('config/settings.json')));
    
  3. Database or Cache Serialization:

    // Store JSON in DB/cache
    $serialized = Json::encode($complexObject);
    cache()->put('key', $serialized, $ttl);
    
    // Retrieve and decode
    $data = Json::decode(cache()->get('key'));
    
  4. Form Data Validation:

    // Validate JSON input before processing
    try {
        $validated = Json::decode($rawInput, Json::DECODE_ASSOC);
        // Proceed with validation logic
    } catch (JsonDecodeException $e) {
        return response()->json(['error' => 'Invalid JSON'], 400);
    }
    

Integration Tips

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

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

    Then inject via constructor:

    public function __construct(private Json $json) {}
    
  • Custom JSON Handling Middleware: Decode JSON payloads in middleware for API routes:

    public function handle($request, Closure $next) {
        if ($request->isJson()) {
            $request->merge(Json::decode($request->getContent(), Json::DECODE_ASSOC));
        }
        return $next($request);
    }
    
  • Fallback for json_encode/json_decode: Replace native functions in legacy code:

    // Before: json_encode($data)
    // After: Json::encode($data)
    

Gotchas and Tips

Pitfalls

  1. Deprecated Package:

    • Last updated in 2014 (archived). Use at your own risk; consider modern alternatives like spatie/array-to-json or Laravel’s built-in json_encode/json_decode with JSON_THROW_ON_ERROR (PHP 8.3+).
  2. Error Handling:

    • The package throws JsonDecodeException for invalid JSON, but no exception is thrown for json_encode failures. Validate output manually:
      $json = Json::encode($data);
      if (json_last_error() !== JSON_ERROR_NONE) {
          throw new \RuntimeException('JSON encode failed');
      }
      
  3. Associative Arrays vs. Objects:

    • Json::DECODE_ASSOC returns arrays, while Json::DECODE_OBJECT returns stdClass. Be explicit to avoid type surprises:
      // Avoid ambiguity
      $data = Json::decode($json, Json::DECODE_ASSOC);
      
  4. No Pretty-Printing:

    • Unlike native json_encode, this package doesn’t support JSON_PRETTY_PRINT. Use PHP’s built-in function if needed:
      echo json_encode($data, JSON_PRETTY_PRINT);
      

Debugging Tips

  • Check JSON Validity: Use json_last_error_msg() to debug decode failures:

    $data = Json::decode($json);
    if (json_last_error() !== JSON_ERROR_NONE) {
        logger()->error('JSON decode error: ' . json_last_error_msg());
    }
    
  • Fallback for Missing Closing Brace: The package catches syntax errors, but log the raw input for debugging:

    catch (JsonDecodeException $e) {
        logger()->error("Invalid JSON: {$json}. Error: {$e->getMessage()}");
    }
    

Extension Points

  1. Custom JSON Options: Extend the class to support additional json_encode flags:

    class ExtendedJson extends Json {
        public static function encode($data, int $options = 0, int $depth = 512) {
            return parent::encode($data, $options | JSON_UNESCAPED_SLASHES);
        }
    }
    
  2. Override Decode Behavior: Modify how decoded data is processed (e.g., type casting):

    class CustomJson extends Json {
        public static function decode($json, $assoc = false, $depth = 512, $flags = 0) {
            $data = parent::decode($json, $assoc, $depth, $flags);
            return is_array($data) ? array_map('strval', $data) : $data;
        }
    }
    
  3. Integration with Laravel’s Jsonable: Create a trait to make Eloquent models compatible:

    trait Jsonable {
        public function toJson() {
            return Json::encode($this->toArray());
        }
    }
    

Configuration Quirks

  • No Config File: The package has no settings; all behavior is hardcoded. For customization, subclass Braincrafted\Json\Json.

  • PSR-4 Compliance: Ensure your autoloader is configured for PSR-4 (Laravel’s default since 5.5). If using older Laravel, verify the namespace resolution.

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.
besmartand-pro/php-quality-config
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
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