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

Laravel-friendly JSONPath implementation for querying and extracting data from JSON and PHP arrays. Supports common JSONPath syntax to filter, traverse, and select values, making it easy to work with complex API responses and nested documents.

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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
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
php-http/client-implementation
phpcr/phpcr-implementation
cucumber/gherkin-monorepo
haydenpierce/class-finder
psr/simple-cache-implementation
uri-template/tests