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

galbar/jsonpath

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

composer require galbar/jsonpath

First Use Case: Querying JSON

use Galbar\JsonPath\JsonPath;

// Sample JSON data (could be from API response, config, or DB)
$data = json_decode('{
    "store": {
        "book": [
            {"category": "reference", "author": "Nigel Rees", "title": "Sayings of the Century"},
            {"category": "fiction", "author": "Evelyn Waugh", "title": "Sword of Honour"}
        ],
        "bicycle": {"color": "red", "price": 19.95}
    }
}');

// Basic query
$jsonPath = new JsonPath();
$books = $jsonPath->find($data, '$.store.book');

Key Starting Points

  1. JsonPath::find() – Core method for querying JSON
  2. JsonPath::get() – Get first matching value (or null)
  3. JsonPath::set() – Update/modify JSON
  4. JsonPath::delete() – Remove nodes

Implementation Patterns

Common Workflows

1. API Response Processing

// Laravel HTTP client response
$response = Http::get('https://api.example.com/data')->json();
$jsonPath = new JsonPath();

// Extract nested data
$items = $jsonPath->find($response, '$.data.items[?(@.status == "active")]');

2. Dynamic Configuration Merging

// Merge config from multiple sources
$baseConfig = config('app.defaults');
$overrideConfig = $jsonPath->get($request->json(), '$.config.overrides');

// Apply overrides
$mergedConfig = array_merge_recursive($baseConfig, $overrideConfig);

3. Database Query Filtering

// Filter Eloquent model attributes
$attributes = $model->toArray();
$filtered = $jsonPath->find($attributes, '$.relationships[?(@.active == true)]');

4. Form Data Validation

// Validate nested form data
$validated = $jsonPath->get($request->all(), '$.user.profile[?(@.age >= 18)]');
if (!$validated) {
    throw new \Exception('User must be 18+');
}

Integration Tips

Laravel Service Providers

// Register as singleton in AppServiceProvider
$this->app->singleton(JsonPath::class, function () {
    return new JsonPath();
});

// Usage in controllers
public function __construct(private JsonPath $jsonPath) {}

Blade Directives (Advanced)

// Custom Blade directive for JSONPath queries
Blade::directive('jsonpath', function ($expression) {
    return "<?php echo app('jsonpath')->get($expression); ?>";
});

// Usage in views
@jsonpath($data, '$.store.book[*].title')

Event Listeners

// Process JSON payloads in events
public function handle(ApiRequestReceived $event)
{
    $jsonPath = new JsonPath();
    $metadata = $jsonPath->get($event->payload, '$.metadata');
    // ...
}

Gotchas and Tips

Common Pitfalls

  1. Regex Syntax Quirks

    • Use raw strings for regex patterns:
      $matches = $jsonPath->find($data, '$..[?(@.name =~ /^test$/)]');
      
    • Escape special characters ($, ., [, ]) in paths.
  2. Case Sensitivity

    • JSON keys are case-sensitive by default. Use regex flags for case-insensitive queries:
      $jsonPath->find($data, '$..[?(@.Name =~ /test/i)]');
      
  3. Empty Results

    • Always check for empty arrays:
      $result = $jsonPath->find($data, '$.nonexistent.path');
      if (empty($result)) { /* handle */ }
      
  4. Array vs. Object Keys

    • Use quotes for non-alphanumeric keys:
      // Correct
      $jsonPath->find($data, '$.user["profile-id"]');
      
      // Incorrect (throws error)
      $jsonPath->find($data, '$.user[profile-id]');
      
  5. Performance with Large JSON

    • Avoid overly complex queries on huge payloads (e.g., $..*).
    • Cache JsonPath instances:
      $jsonPath = new JsonPath(); // Reuse this instance
      

Debugging Tips

  1. Validate JSONPath Syntax

  2. Log Queries for Debugging

    \Log::debug('Query:', [
        'path' => '$.store.book[*].title',
        'data' => $data,
        'result' => $jsonPath->find($data, '$.store.book[*].title')
    ]);
    
  3. Handle Malformed JSON

    • Always validate input JSON:
      $data = json_decode($request->getContent(), true);
      if (json_last_error() !== JSON_ERROR_NONE) {
          throw new \InvalidArgumentException('Invalid JSON');
      }
      

Extension Points

  1. Custom Operators

    • Extend the parser by subclassing Galbar\JsonPath\JsonPath and overriding parse():
      class CustomJsonPath extends JsonPath {
          protected function parse($path) {
              // Add custom logic here
              return parent::parse($path);
          }
      }
      
  2. Plugin System

    • Register custom functions via the addFunction() method:
      $jsonPath->addFunction('upper', function ($value) {
          return strtoupper($value);
      });
      
      // Usage in query
      $jsonPath->find($data, '$..[?(@.name == upper("test"))]');
      
  3. Integration with Laravel Collections

    • Create a macro for Collections:
      \Illuminate\Support\Collection::macro('jsonPath', function ($path) {
          $jsonPath = new JsonPath();
          return $jsonPath->find($this->toArray(), $path);
      });
      
      // Usage
      $collection->jsonPath('$.data.items[*].id');
      
  4. Type-Safe Queries

    • Combine with Laravel’s data_get() for type safety:
      $value = data_get($jsonPath->get($data, '$.path.to.value'), 'default');
      
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
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
christhompsontldr/laravel-inky