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

peekmo/jsonpath

peekmo/jsonpath adds JSONPath querying to PHP/Laravel, letting you select, filter, and extract values from complex JSON/arrays using familiar JSONPath expressions. Useful for API responses, config inspection, and transforming nested data quickly.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the package via Composer:

    composer require peekmo/jsonpath
    

    No service provider or facade registration is required—use it as a standalone library.

  2. First Use Case Query a JSON string or array with JsonPath syntax:

    use Peekmo\JsonPath\JsonPath;
    
    $json = '{"store": {"book": [{"title": "PHP", "price": 10}, {"title": "Laravel", "price": 20}]}}';
    $result = JsonPath::search($json, '$.store.book[*].title');
    // Returns: ["PHP", "Laravel"]
    
  3. Where to Look First

    • JsonPath Syntax Guide (Stefan Goessner’s spec).
    • Peekmo\JsonPath\JsonPath class methods: search(), evaluate(), find().
    • Test cases in the source repo (if available) for edge cases.

Implementation Patterns

Core Workflows

  1. Querying Nested Data Use search() for arrays of results or evaluate() for single values:

    $data = ['users' => [['name' => 'Alice'], ['name' => 'Bob']]];
    $names = JsonPath::search($data, '$.users[*].name'); // ["Alice", "Bob"]
    $firstName = JsonPath::evaluate($data, '$.users[0].name'); // "Alice"
    
  2. Dynamic Paths Build paths programmatically (e.g., for API responses):

    $path = sprintf('$.data.items[?(@.price > %d)]', $minPrice);
    $expensiveItems = JsonPath::search($apiResponse, $path);
    
  3. Integration with Laravel

    • Requests: Parse JSON responses from APIs:
      $response = Http::get('https://api.example.com/data');
      $filteredData = JsonPath::search($response->json(), '$.results[*].id');
      
    • Eloquent: Extract attributes from JSON columns:
      $user = User::whereJsonContains('metadata', '$.preferences.theme')->first();
      $theme = JsonPath::evaluate($user->metadata, '$.preferences.theme');
      
  4. Validation Use JsonPath to validate API payloads or database records:

    $requiredPath = '$.user.email';
    if (empty(JsonPath::evaluate($request->json(), $requiredPath))) {
        return response()->json(['error' => 'Email missing'], 400);
    }
    

Advanced Patterns

  • Wildcards and Filters:
    // Filter books priced > 15
    $expensiveBooks = JsonPath::search($json, '$.store.book[?(@.price > 15)]');
    
  • Custom Functions: Extend the parser by implementing Peekmo\JsonPath\Functions\FunctionInterface (see source).

Gotchas and Tips

Common Pitfalls

  1. Archived Package

    • Last release in 2014; test thoroughly for edge cases (e.g., circular references, non-standard JSON).
    • Consider forking or using alternatives like mtdowling/jsonpath-php if critical bugs arise.
  2. Path Syntax Strictness

    • No $ prefix in arrays: $.store.book works, but $.book fails if book is a direct child of the root array.
    • Bracket vs. Dot Notation: Prefer $.store.book[0] over $.store.book.0 for consistency.
  3. Performance

    • Avoid deep nesting or overly complex paths in loops (e.g., $.a.b.c[*].d[*].e).
    • Cache parsed results if querying the same path repeatedly.
  4. Edge Cases

    • Null Values: JsonPath::search() returns null for missing paths; handle with isset() or array_filter().
    • Non-JSON Input: Pass arrays directly; strings must be valid JSON (use json_decode() first if unsure).

Debugging Tips

  • Validate JSON: Use json_last_error() if paths fail unexpectedly.
  • Test Paths: Use online tools like JsonPath Online Evaluator to verify syntax.
  • Enable Errors: Set error_reporting(E_ALL) to catch silent failures (e.g., malformed paths).

Extension Points

  1. Custom Functions Register a function to handle domain-specific logic:

    JsonPath::addFunction('isAdmin', function ($value) {
        return $value === 'admin';
    });
    // Usage: $.users[?isAdmin(@.role)]
    
  2. Override Defaults Extend the JsonPath class to modify behavior (e.g., case-insensitive keys):

    class CustomJsonPath extends JsonPath {
        protected function normalizeKey($key) {
            return strtolower($key);
        }
    }
    
  3. Laravel Helpers Create a helper trait for reusable logic:

    trait JsonPathHelper {
        public function jsonPath($json, $path) {
            return JsonPath::search($json, $path);
        }
    }
    
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.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope