Weave 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

herrera-io/json

PHP library for working with JSON data: read, write, validate, and manipulate JSON structures with a simple API. Useful for encoding/decoding, handling JSON files, and keeping JSON processing consistent across your applications.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require herrera-io/json
    

    Ensure the package is auto-discoverable (Laravel 5.5+ handles this automatically).

  2. First Use Case: Replace raw json_decode() with the package’s validator and decoder:

    use HerreraIo\Json\Facades\Json;
    
    $jsonString = '{"name":"John","age":30}';
    $data = Json::decode($jsonString); // Returns associative array
    
  3. Where to Look First:

    • Facade: Json (for encode/decode).
    • Validator: Json::validate() for schema-like checks.
    • Exceptions: JsonException for error handling.
    • Documentation: Check the src/ directory for core classes (Json.php, JsonValidator.php).

Implementation Patterns

Core Usage Patterns

  1. Strict Decoding with Validation:

    try {
        $data = Json::decode($request->getContent(), true, 512); // 512 = max depth
        // Proceed if valid
    } catch (JsonException $e) {
        abort(422, 'Invalid JSON: ' . $e->getMessage());
    }
    
  2. Custom Serialization: Override default behavior for Laravel models/collections:

    Json::setEncoder(function ($data) {
        return json_encode($data, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);
    });
    
  3. API Request Validation: Validate incoming JSON against expected structure:

    $validator = new \HerreraIo\Json\JsonValidator();
    if (!$validator->validate($request->getContent(), [
        'required' => ['user_id', 'action'],
        'user_id' => ['integer'],
        'action' => ['string', 'min:3']
    ])) {
        throw new \Exception('Invalid payload');
    }
    
  4. Laravel Integration:

    • Form Requests:
      public function rules()
      {
          return [
              'data' => ['required', function ($attribute, $value) {
                  return Json::validate($value, ['type' => 'object']);
              }],
          ];
      }
      
    • API Resources:
      public function toArray($request)
      {
          return Json::encode($this->resource->toArray());
      }
      
  5. Configuration Handling: Validate JSON configs during bootstrapping:

    public function boot()
    {
        $config = config('app.custom_json');
        Json::validate($config, ['type' => 'object']);
    }
    

Workflow Tips

  • Use Facades for Convenience:
    // Instead of:
    $json = new \HerreraIo\Json\Json();
    // Use:
    $data = Json::decode($jsonString);
    
  • Leverage Exceptions: Catch JsonException for malformed input:
    try {
        $data = Json::decode($input);
    } catch (JsonException $e) {
        Log::error('JSON decode failed: ' . $e->getMessage());
        return response()->json(['error' => 'Invalid data'], 400);
    }
    
  • Batch Processing: For arrays of JSON strings:
    $validated = array_map(function ($json) {
        return Json::decode($json);
    }, $jsonArray);
    

Gotchas and Tips

Pitfalls

  1. Validation Overhead:

    • The package’s validator may reject valid JSON if rules are too strict. Test edge cases like:
      {"key": null, "empty": ""}
      
    • Fix: Adjust validation rules or use Json::decode() without validation.
  2. Performance:

    • Avoid using the validator for large payloads (e.g., bulk API responses). Native json_decode() is faster.
    • Tip: Cache decoded JSON if reused:
      $cacheKey = 'json_'.$hash;
      $data = Cache::remember($cacheKey, 3600, function () use ($json) {
          return Json::decode($json);
      });
      
  3. Circular References:

    • The package may not handle circular references in objects (unlike symfony/serializer).
    • Workaround: Use JSON_THROW_ON_ERROR with native functions or implement a custom encoder.
  4. Laravel-Specific Types:

    • Custom types (e.g., Carbon, Collection) may not serialize/deserialize as expected.
    • Solution: Register custom handlers:
      Json::setEncoder(function ($data) {
          return json_encode($data, JSON_THROW_ON_ERROR);
      });
      
  5. Error Messages:

    • Default error messages may not be user-friendly. Override them:
      Json::setExceptionHandler(function ($e) {
          throw new \Exception('Invalid JSON: ' . $e->getMessage());
      });
      

Debugging Tips

  1. Enable Strict Mode: Use JSON_THROW_ON_ERROR for immediate feedback:

    $data = Json::decode($json, true, 512, JSON_THROW_ON_ERROR);
    
  2. Log Validation Errors:

    $validator = new \HerreraIo\Json\JsonValidator();
    if (!$validator->validate($json)) {
        Log::error('Validation failed:', [
            'errors' => $validator->getErrors(),
            'json' => $json
        ]);
    }
    
  3. Compare with Native Functions: For debugging, test against PHP’s native functions:

    $nativeResult = json_decode($json, true);
    $packageResult = Json::decode($json);
    dd($nativeResult === $packageResult);
    

Extension Points

  1. Custom Validators: Extend JsonValidator for domain-specific rules:

    class UserJsonValidator extends \HerreraIo\Json\JsonValidator
    {
        public function validateUser($json)
        {
            return $this->validate($json, [
                'required' => ['email', 'role'],
                'email' => ['email'],
                'role' => ['enum:admin,user']
            ]);
        }
    }
    
  2. Custom Encoders/Decoders: Replace default behavior:

    Json::setEncoder(function ($data) {
        return json_encode($data, JSON_UNESCAPED_UNICODE);
    });
    
    Json::setDecoder(function ($json, $assoc = true, $depth = 512) {
        return json_decode($json, $assoc, $depth, JSON_THROW_ON_ERROR);
    });
    
  3. Integration with Laravel Validation: Create a custom validation rule:

    use HerreraIo\Json\Facades\Json;
    
    class ValidJson implements Rule
    {
        public function passes($attribute, $value)
        {
            return Json::validate($value, ['type' => 'object']);
        }
    }
    

    Usage:

    'data' => ['required', new ValidJson],
    

Configuration Quirks

  1. Default Settings:

    • The package uses JSON_THROW_ON_ERROR by default, which may not match your error-handling strategy.
    • Fix: Set a global handler:
      Json::setExceptionHandler(function ($e) {
          return json_decode($e->getMessage(), true);
      });
      
  2. Depth Limits:

    • Default recursion depth is 512. Adjust for deep objects:
      $data = Json::decode($json, true, 1000); // Increase depth
      
  3. Associative Arrays:

    • Json::decode($json, true) returns associative arrays, but nested objects may still be stdClass.
    • Tip: Use json_decode($json, true) for consistent behavior if needed.

Laravel-Specific Tips

  1. Request Handling: Validate JSON in App\Http\Middleware\ValidateJson:

    public function handle($request, Closure $next)
    {
        if ($request->isJson() && !$request->hasValidJson()) {
            abort(422, 'Invalid JSON payload');
        }
        return $next($request);
    }
    
  2. API Resources: Override toJson() for custom serialization:

    public function toJson($request)
    {
        return Json::encode($this->resource->toArray());
    }
    
  3. Service Providers: Bind the package globally:

    public function register()
    {
        $this->app->singleton('json', function () {
            return new \HerreraIo\Json\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.
socialdept/tenant-domains
tautvydasr/blade-class-names
socialdept/color-scales
maherelgamil/controller
coleus/widgets
coleus/table
coleus/users
coleus/music
coleus/health
coleus/calendar
coleus/notes
coleus/support
coleus/settings
coleus/apps
seampact/laravel
emmyconceptng/laravel-ng-postcode
jjsquady/round-robin
skyraptor/chatter
edlugz/sasapay
abbasudo/artisan-route