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

balping/json-raw-encoder

Laravel helper for encoding JSON while preserving “raw” fragments (like JS functions or pre-encoded JSON) without extra quoting/escaping. Handy for configs and API payloads when parts must stay untouched, with a simple API and reliable output.

Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require balping/json-raw-encoder
    

    Add to composer.json if not auto-loaded:

    "autoload": {
        "psr-4": {
            "App\\": "app/",
            "Balping\\JsonRawEncoder\\": "vendor/balping/json-raw-encoder/src/"
        }
    }
    

    Run composer dump-autoload.

  2. First Use Case Encode an array containing raw JavaScript objects (e.g., callbacks, functions) without JSON serialization errors:

    use Balping\JsonRawEncoder\JsonRawEncoder;
    
    $data = [
        'name' => 'John',
        'callback' => 'function() { console.log("Hello!"); }'
    ];
    
    $encoder = new JsonRawEncoder();
    $json = $encoder->encode($data);
    // Output: {"name":"John","callback":function() { console.log("Hello!"); }}
    
  3. Where to Look First

    • Core Class: JsonRawEncoder (handles encoding logic).
    • Configuration: No config file; defaults are sensible.
    • Documentation: Check the GitHub repo (if unarchived) or source code for edge cases.

Implementation Patterns

Basic Usage

Replace Laravel’s default JSON encoder (e.g., in API responses, Blade views, or AJAX handlers):

// In a controller or service
return response()->json($encoder->encode($yourDataWithRawJS));

Integration with Laravel’s JSON Responses

Override the default JSON response macro:

use Balping\JsonRawEncoder\JsonRawEncoder;

$encoder = new JsonRawEncoder();
Response::macro('jsonRaw', function ($data, $status = 200, array $headers = [], $options = 0) use ($encoder) {
    return $this->json($encoder->encode($data), $status, $headers, $options);
});

Usage:

return response()->jsonRaw(['callback' => 'alert("Hi!");']);

Blade Directives

Create a custom Blade directive for JSON encoding:

// In AppServiceProvider@boot()
Blade::directive('jsonraw', function ($expression) {
    return "<?php echo (new \\Balping\\JsonRawEncoder\\JsonRawEncoder())->encode({$expression}); ?>";
});

Usage in Blade:

<script>
    const data = @jsonraw($yourArrayWithRawJS);
</script>

Workflow for Complex Data

  1. Preprocess Data: Clean or transform data before encoding (e.g., sanitize strings, validate JS syntax).
  2. Fallback Handling: Wrap encoding in a try-catch to fall back to json_encode for invalid inputs:
    try {
        return $encoder->encode($data);
    } catch (\Exception $e) {
        return json_encode($data); // Fallback
    }
    
  3. Testing: Test with edge cases like:
    • Nested arrays with raw JS.
    • Mixed PHP objects and raw JS.
    • Unicode or special characters in JS strings.

Gotchas and Tips

Pitfalls

  1. Security Risks

    • Raw JS in JSON responses can expose XSS vulnerabilities if user input is directly embedded. Always sanitize dynamic JS strings:
      $safeJs = htmlspecialchars($userInput, ENT_QUOTES, 'UTF-8');
      $data['callback'] = $safeJs;
      
    • Avoid using this for untrusted data (e.g., user-submitted JS).
  2. Browser Compatibility

    • Some older browsers may not handle raw JS objects in JSON strings. Test in target environments.
  3. Circular References

    • The package doesn’t handle circular references. Use json_encode with JSON_THROW_ON_ERROR or a library like spatie/array-to-object for complex objects.
  4. False Positives

    • Strings that look like JS (e.g., 'function() { return "text"; }') will be encoded literally. Only use this for actual raw JS.

Debugging Tips

  1. Validate Input Check if the input is a string that could be JS before encoding:

    if (is_string($data['callback']) && stripos($data['callback'], 'function') !== false) {
        $json = $encoder->encode($data);
    } else {
        $json = json_encode($data);
    }
    
  2. Log Encoded Output Log the final JSON string to verify raw JS is preserved:

    \Log::debug('Encoded JSON:', [$encoder->encode($data)]);
    
  3. Extension Points

    • Custom Encoder: Extend JsonRawEncoder to add preprocessing:
      class CustomEncoder extends JsonRawEncoder {
          protected function encodeValue($value) {
              if (is_string($value) && $this->isValidJs($value)) {
                  return $value; // Preserve raw JS
              }
              return parent::encodeValue($value);
          }
      
          private function isValidJs(string $str): bool {
              // Add validation logic (e.g., check for balanced parentheses).
              return true;
          }
      }
      
  4. Configuration Quirks

    • No config file, but you can inject dependencies (e.g., a JS validator) via constructor:
      $encoder = new JsonRawEncoder(new JsValidator());
      
  5. Performance

    • For large datasets, benchmark against json_encode + manual string replacement (e.g., str_replace for known JS patterns). This package may add overhead for simple cases.
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
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
twbs/bootstrap4