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

Hjson Laravel Package

laktak/hjson

PHP library for parsing and generating Hjson (Human JSON). Read relaxed JSON with comments, optional commas, and unquoted keys/strings; stringify back to Hjson. Supports preserving whitespace/comments for round-trip editing. Install via Composer: laktak/hjson.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation

    composer require laktak/hjson
    

    Add to composer.json if using a monorepo or custom setup.

  2. First Parse Create a .hjson file (e.g., config/app.hjson):

    # App Configuration
    app_name: "My App"
    debug: true
    env: [
      "local",
      "staging"
    ]
    

    Parse it in a Laravel service provider or controller:

    use HJSON\HJSONParser;
    
    $parser = new HJSONParser();
    $config = $parser->parse(file_get_contents(base_path('config/app.hjson')));
    
  3. First Use Case Replace JSON config files (e.g., config/app.php) with .hjson equivalents. Leverage comments and relaxed syntax for better readability:

    # Database Configuration
    database: {
      driver: "mysql",
      host: "127.0.0.1",
      port: 3306,
      # Uncomment for production
      # username: "prod_user",
      # password: "prod_pass"
    }
    

Implementation Patterns

Workflows

  1. Config Files

    • Replace Laravel’s JSON config files (e.g., config/mail.json) with .hjson:
      # Mail Configuration
      driver: "smtp"
      host: "mail.example.com"
      port: 587
      encryption: "tls"
      # Credentials (use env vars in production)
      username: "user@example.com"
      password: "secret"
      
    • Load in config/app.php:
      $mailConfig = (new HJSONParser())->parse(file_get_contents(__DIR__.'/mail.hjson'));
      return array_merge(config(), $mailConfig);
      
  2. API Responses

    • Use HJSONStringifier to generate human-readable responses for debugging:
      use HJSON\HJSONStringifier;
      
      $stringifier = new HJSONStringifier();
      return response($stringifier->stringify($data), 200, ['Content-Type' => 'application/hjson']);
      
  3. Environment-Specific Configs

    • Store environment-specific overrides in .hjson files (e.g., config/local.hjson):
      # Local Overrides
      debug: true
      log_level: "debug"
      
    • Merge dynamically:
      $baseConfig = require __DIR__.'/app.php';
      $envConfig = (new HJSONParser())->parse(file_get_contents(__DIR__.'/local.hjson'));
      return array_merge_recursive($baseConfig, $envConfig);
      
  4. Validation with Comments

    • Use HJSON for validation rules or API specs with embedded comments:
      # User Validation Rules
      rules: {
        name: "required|string|max:255",
        email: "required|email|unique:users",
        # Password rules (commented out for demo)
        # password: "required|min:8|confirmed"
      }
      

Integration Tips

  • Service Providers: Register HJSON parsers as singletons in AppServiceProvider:

    $this->app->singleton(HJSONParser::class, function () {
        return new HJSONParser();
    });
    

    Inject via constructor:

    public function __construct(private HJSONParser $parser) {}
    
  • Artisan Commands: Parse HJSON for CLI tools:

    $config = $this->parser->parse(file_get_contents($this->laravel->basePath('config/cli.hjson')));
    
  • Testing: Use HJSON for test data with comments:

    # Test User Data
    users: [
      {
        id: 1,
        name: "John Doe",
        # Active status (true/false)
        active: true
      }
    ]
    

Gotchas and Tips

Pitfalls

  1. Whitespace Sensitivity

    • Unlike JSON, HJSON preserves whitespace and comments by default. Use keepWsc: false in parse() to strip them:
      $parser->parse($text, ['keepWsc' => false]);
      
    • Tip: Set a default config in your parser instance:
      $parser = new HJSONParser(['keepWsc' => false]);
      
  2. String Quotes

    • HJSON allows unquoted strings (e.g., key: value), but this can cause issues with:
      • Special characters (e.g., key: hello world fails if world is a reserved word).
      • Fix: Use quotes for ambiguous values or enable strict mode (if available in future versions).
  3. Optional Commas

    • Trailing commas (e.g., {"a": 1,}) are allowed but may cause issues with:
      • Older JSON parsers or tools.
      • Tip: Validate output with json_encode() if interoperability is needed:
        $hjsonData = $parser->parse($text);
        json_encode($hjsonData); // Throws error if invalid
        
  4. File Encoding

    • HJSON files must be UTF-8 encoded. Non-UTF-8 files may throw parsing errors.
    • Tip: Add a .editorconfig to enforce UTF-8:
      root = true
      
      [*]
      charset = utf-8
      
  5. Nested Comments

    • HJSON supports /* */ and # comments, but nested /* */ comments are not allowed:
      /* Outer comment
      /* Inner comment */ // ERROR
      */
      

Debugging

  1. Parse Errors

    • Use try-catch to handle malformed HJSON:
      try {
          $data = $parser->parse($text);
      } catch (\HJSON\HJSONException $e) {
          Log::error("HJSON Parse Error: " . $e->getMessage());
          throw new \RuntimeException("Invalid config file", 0, $e);
      }
      
  2. Stringify Issues

    • HJSONStringifier may not preserve all HJSON features (e.g., comments). Use json_encode() for strict JSON output:
      $json = json_encode($data, JSON_PRETTY_PRINT);
      

Extension Points

  1. Custom Parsing Options

    • Extend HJSONParser to add custom options (e.g., trimTrailingCommas):
      class CustomHJSONParser extends HJSONParser {
          public function parse($text, array $options = []) {
              $options['trimTrailingCommas'] = true;
              return parent::parse($text, $options);
          }
      }
      
  2. File Watching

    • Use Laravel’s file caching with HJSON:
      $config = $this->parser->parse(file_get_contents($path));
      Cache::remember("hjson_{$path}", now()->addHours(1), fn() => $config);
      
  3. IDE Support

    • Add .hjson to your IDE’s JSON language support (e.g., VSCode) for syntax highlighting.
    • Tip: Use the Hjson VSCode extension for full support.
  4. Validation

    • Combine with Laravel’s Validator for HJSON-based rules:
      $rules = (new HJSONParser())->parse(file_get_contents(__DIR__.'/rules.hjson'));
      $validator = Validator::make($request->all(), $rules);
      

Config Quirks

  • Default Options: The parser defaults to keepWsc: true. Explicitly set options to avoid surprises:
    $parser = new HJSONParser(['keepWsc' => false]);
    
  • Empty Values: ? in HJSON becomes null in PHP. Handle null checks explicitly:
    if (is_null($config['optional_key'])) {
        // Handle missing value
    }
    
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
codifyo/ts-generator-bundle
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
christhompsontldr/laravel-inky
spatie/mailcoach-vapor