composer require galbar/jsonpath
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');
JsonPath::find() – Core method for querying JSONJsonPath::get() – Get first matching value (or null)JsonPath::set() – Update/modify JSONJsonPath::delete() – Remove nodes// 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")]');
// Merge config from multiple sources
$baseConfig = config('app.defaults');
$overrideConfig = $jsonPath->get($request->json(), '$.config.overrides');
// Apply overrides
$mergedConfig = array_merge_recursive($baseConfig, $overrideConfig);
// Filter Eloquent model attributes
$attributes = $model->toArray();
$filtered = $jsonPath->find($attributes, '$.relationships[?(@.active == true)]');
// Validate nested form data
$validated = $jsonPath->get($request->all(), '$.user.profile[?(@.age >= 18)]');
if (!$validated) {
throw new \Exception('User must be 18+');
}
// Register as singleton in AppServiceProvider
$this->app->singleton(JsonPath::class, function () {
return new JsonPath();
});
// Usage in controllers
public function __construct(private JsonPath $jsonPath) {}
// 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')
// Process JSON payloads in events
public function handle(ApiRequestReceived $event)
{
$jsonPath = new JsonPath();
$metadata = $jsonPath->get($event->payload, '$.metadata');
// ...
}
Regex Syntax Quirks
$matches = $jsonPath->find($data, '$..[?(@.name =~ /^test$/)]');
$, ., [, ]) in paths.Case Sensitivity
$jsonPath->find($data, '$..[?(@.Name =~ /test/i)]');
Empty Results
$result = $jsonPath->find($data, '$.nonexistent.path');
if (empty($result)) { /* handle */ }
Array vs. Object Keys
// Correct
$jsonPath->find($data, '$.user["profile-id"]');
// Incorrect (throws error)
$jsonPath->find($data, '$.user[profile-id]');
Performance with Large JSON
$..*).JsonPath instances:
$jsonPath = new JsonPath(); // Reuse this instance
Validate JSONPath Syntax
Log Queries for Debugging
\Log::debug('Query:', [
'path' => '$.store.book[*].title',
'data' => $data,
'result' => $jsonPath->find($data, '$.store.book[*].title')
]);
Handle Malformed JSON
$data = json_decode($request->getContent(), true);
if (json_last_error() !== JSON_ERROR_NONE) {
throw new \InvalidArgumentException('Invalid JSON');
}
Custom Operators
Galbar\JsonPath\JsonPath and overriding parse():
class CustomJsonPath extends JsonPath {
protected function parse($path) {
// Add custom logic here
return parent::parse($path);
}
}
Plugin System
addFunction() method:
$jsonPath->addFunction('upper', function ($value) {
return strtoupper($value);
});
// Usage in query
$jsonPath->find($data, '$..[?(@.name == upper("test"))]');
Integration with Laravel Collections
\Illuminate\Support\Collection::macro('jsonPath', function ($path) {
$jsonPath = new JsonPath();
return $jsonPath->find($this->toArray(), $path);
});
// Usage
$collection->jsonPath('$.data.items[*].id');
Type-Safe Queries
data_get() for type safety:
$value = data_get($jsonPath->get($data, '$.path.to.value'), 'default');
How can I help you explore Laravel packages today?