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

Jsonpath Laravel Package

flow/jsonpath

PHP JSONPath implementation for querying and extracting data with XPath-like expressions. Object-oriented, tokenized/cached parser (no eval) and works with arrays, objects, and ArrayAccess. Note: this repo is unmaintained; see SoftCreatR/JSONPath.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require flow/jsonpath
    

    (Note: The package is archived; use SoftCreatR/JSONPath for active maintenance.)

  2. Basic Usage:

    use Flow\JSONPath\JSONPath;
    
    $data = ['store' => ['books' => [
        ['title' => 'Book 1', 'price' => 10],
        ['title' => 'Book 2', 'price' => 20]
    ]]];
    
    $jsonPath = new JSONPath($data);
    $results = $jsonPath->find('$.store.books[*].title');
    // Returns: ['Book 1', 'Book 2']
    
  3. First Use Case:

    • Query nested JSON/array structures (e.g., API responses, config files).
    • Example: Extract all book titles from a Laravel API response:
      $response = json_decode($apiResponse);
      $titles = (new JSONPath($response))->find('$.data.books[*].title');
      

Implementation Patterns

Usage Patterns

  1. Chaining Queries: Use find() to chain multiple JSONPath queries:

    $books = $jsonPath->find('$.store.books');
    $expensiveBooks = $jsonPath->find('$..[?(@.price > 15)]');
    
  2. Recursive Descent (..): Traverse deeply nested structures:

    $allAuthors = $jsonPath->find('$..author'); // Finds all authors recursively
    
  3. Array Slicing: Extract subarrays using slice notation:

    $firstTwoBooks = $jsonPath->find('$..books[0:2]'); // First two books
    $everyThirdBook = $jsonPath->find('$..books[::3]'); // Every third book
    
  4. Filtering with Predicates: Filter results dynamically:

    $cheapBooks = $jsonPath->find('$..books[?(@.price < 10)]');
    
  5. Magic Method Access (Caution): Enable __get() support for objects (use sparingly):

    $jsonPath = new JSONPath($object, JSONPath::ALLOW_MAGIC);
    

Workflows

  • API Response Processing: Parse Laravel API responses (e.g., from Http::get() or axios):

    $response = Http::get('api/books')->json();
    $titles = (new JSONPath($response))->find('$.data[*].title');
    
  • Configuration Extraction: Extract values from nested config arrays (e.g., config('services.api')):

    $config = config('services');
    $apiKeys = (new JSONPath($config))->find('$..api[*].key');
    
  • Form Data Validation: Validate nested form data (e.g., from request()->all()):

    $data = request()->all();
    $validBooks = (new JSONPath($data))->find('$..books[?(@.price > 0)]');
    

Integration Tips

  • Laravel Service Provider: Bind the package globally for reuse:

    // app/Providers/AppServiceProvider.php
    public function register()
    {
        $this->app->singleton('jsonpath', function () {
            return new \Flow\JSONPath\JSONPath;
        });
    }
    

    Usage:

    $results = app('jsonpath')->find($data, '$.path');
    
  • Eloquent Relationships: Query nested Eloquent relationships:

    $user = User::with('posts.comments')->find(1);
    $comments = (new JSONPath($user))->find('$..comments[*].body');
    
  • Testing: Use in PHPUnit tests to assert nested data:

    $this->assertEquals(['Book 1', 'Book 2'], (new JSONPath($data))->find('$.store.books[*].title'));
    

Gotchas and Tips

Pitfalls

  1. Archived Package:

    • The original repo is archived. Use SoftCreatR/JSONPath for updates.
    • Fork or maintain your own branch if critical fixes are needed.
  2. Magic Method Quirks:

    • ALLOW_MAGIC can lead to unpredictable behavior (e.g., wildcard queries ignore private properties).
    • Avoid unless you control the object’s __get() implementation.
  3. Slice Notation Breaking Change:

    • Version 0.5.0 fixed slice notation (e.g., [0:2:5]). Older code may break if relying on the buggy implementation.
  4. No Multiple String Indices:

    • Unsupported syntax: $[name,year] or $["name","year"]. Use dot notation ($.name.year) instead.
  5. Script Expressions:

    • No eval() support. Use only supported operators (==, !=, <, >) in predicates.

Debugging

  • Tokenization Errors:

    • If queries fail silently, enable debug mode by inspecting the lexer tokens:
      $lexer = new \Flow\JSONPath\Lexer('$.store..price');
      $tokens = $lexer->getTokens();
      dd($tokens); // Debug token stream
      
  • Path Not Found:

    • Verify paths with exists():
      if ((new JSONPath($data))->exists('$.store.books')) {
          // Path exists
      }
      
  • Performance:

    • Token caching avoids re-parsing expressions. For heavy usage, ensure the $data object is immutable or cloned per query to avoid side effects.

Tips

  1. Laravel Collections Integration: Convert results to Laravel Collections for chaining:

    $results = collect((new JSONPath($data))->find('$.path'));
    $filtered = $results->filter(fn($item) => $item > 10);
    
  2. Custom Data Structures: Works with ArrayAccess objects (e.g., Laravel’s Arrayable):

    $arrayable = new class implements ArrayAccess { ... };
    $results = (new JSONPath($arrayable))->find('$.key');
    
  3. Performance Optimization:

    • Pre-compile frequent queries:
      $jsonPath = new JSONPath($data);
      $cachedQuery = $jsonPath->compile('$.store.books[*].title');
      $results = $cachedQuery->evaluate($data);
      
  4. Error Handling:

    • Wrap queries in try-catch for malformed paths:
      try {
          $results = (new JSONPath($data))->find('$.invalid.path');
      } catch (\Flow\JSONPath\Exception\RuntimeException $e) {
          Log::error($e->getMessage());
      }
      
  5. Alternative for Advanced Use 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