PHPackages                             galbar/jsonpath - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Parsing &amp; Serialization](/categories/parsing)
4. /
5. galbar/jsonpath

ActiveLibrary[Parsing &amp; Serialization](/categories/parsing)

galbar/jsonpath
===============

JSONPath implementation for querying and updating JSON objects

3.0(3y ago)2136.4M—7.2%39[3 issues](https://github.com/Galbar/JsonPath-PHP/issues)[2 PRs](https://github.com/Galbar/JsonPath-PHP/pulls)20Apache-2.0PHPPHP &gt;=5.4CI failing

Since Sep 16Pushed 1y ago12 watchersCompare

[ Source](https://github.com/Galbar/JsonPath-PHP)[ Packagist](https://packagist.org/packages/galbar/jsonpath)[ RSS](/packages/galbar-jsonpath/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (10)Dependencies (3)Versions (17)Used By (20)

JsonPath
========

[](#jsonpath)

[![Build Status](https://github.com/Galbar/JsonPath-PHP/actions/workflows/php.yml/badge.svg)](https://github.com/Galbar/JsonPath-PHP/actions/workflows/php.yml)[![Latest Stable Version](https://camo.githubusercontent.com/20c3dc344f5ab5d3d9054e9ed9f12bcfb5ae04198d534e309fd3a8766f0255a5/68747470733a2f2f706f7365722e707567782e6f72672f67616c6261722f6a736f6e706174682f762f737461626c65)](https://packagist.org/packages/galbar/jsonpath)[![License](https://camo.githubusercontent.com/4b8eb2aef1d68021246c904a36684f233a65b04ab257216927e2423cdfed5755/68747470733a2f2f706f7365722e707567782e6f72672f67616c6261722f6a736f6e706174682f6c6963656e7365)](https://packagist.org/packages/galbar/jsonpath)

This is a [JSONPath](http://goessner.net/articles/JsonPath/) implementation for PHP.

This implementation features all elements in the specification except the `()` operator (in the spcecification there is the `$..a[(@.length-1)]`, but this can be achieved with `$..a[-1]` and the latter is simpler).

In case of no matches for the query it will return an empty array.

Features
========

[](#features)

This implementation has the following features:

- Regex match key (p.e. `$.*[?(/^bo{2}k$/)]` or `$[?(/a\wthors/)]`).
- Regex match value comparisons (p.e. `$.store.book[?(@.author =~ /.*Tolkien/)]`)
- For the child operator `[]` there is no need to surround child names with quotes (p.e. `$[store][book, bicycle]`) except if the name of the field is a non-valid javascript variable name.
- `.length` can be used to get the length of a string, get the length of an array and to check if a node has children.
- The `in` operator allows filtering for a value in a specified list: `$..[?(@.author in ["Nigel Rees", "Evelyn Waugh", $.store.book[3].author])]`
- Object oriented implementation.
- **Get**, **set** and **add** operations.
- Magic methods implemented:
    - `__get`: `$obj->{'$...'}`.
    - `__set`: `$obj->{'$...'} = $val`.
    - `__toString`: `echo $obj` prints the json representation of the JsonObject.
- Not using `eval()`.

Installation
============

[](#installation)

To install JsonPath you will need to be using Composer in your project. To install it please see the [docs](https://getcomposer.org/download/).

```
composer require galbar/jsonpath
```

Usage
=====

[](#usage)

In every file you use it add:

```
use JsonPath\JsonObject;
```

Now you can create an instance of JsonObject and use it:

```
// $json can be a string containing json, a PHP array, a PHP object or null.
// If $json is null (or not present) the JsonObject will be empty.
$jsonObject = new JsonObject();
// or
$jsonObject = new JsonObject($json);

// get
$obj->get($jsonPath);
$obj->{'$.json.path'};

// set
$obj->set($jsonPath, $value);
$obj->{'$.json.path'} = $value;

// get the json representation
$obj->getJson();
$str = (string)$obj;
echo $obj;

// get the PHP array representation
$obj->getValue();

// add values
$obj->add($jsonPath, $value[, $field]);

// remove values
$obj->remove($jsonPath, $field);
```

SmartGet
--------

[](#smartget)

When creating a new instance of JsonObject, you can pass a second parameter to the constructor. This sets the behaviour of the instance to use SmartGet.

What SmartGet does is to determine if the given JsonPath branches at some point, if it does it behaves as usual; otherwise, it will directly return the value pointed by the given path (not the array containing it) or `false` if not found.

GetJsonObjects
--------------

[](#getjsonobjects)

Sometimes you need to access multiple values of a subobject that has a long prefix (p.e. `$.a.very.long.prefix.for.[*].object`), in this case you would first get said object and make a JsonObject of it and then access its properties.

Now if you want to edit the object (set or add values) and want these changes to affect the original object, the way of doing this is by using `JsonObject::getJsonObjects($jsonpath)`. This method works the same way get does, but it will return the results as JsonObject instances containing a reference to the value in the source JsonObject.

JsonPath Language
=================

[](#jsonpath-language)

This library implements the following specification:

```
var_name¹   = /^\.([\p{L}\p{N}\_\$][\p{L}\p{N}\_\-\$]*|\*)(.*)/u
number      = ([0-9]+(\.[0-9]*) | ([0-9]*\.[0-9]+))
string      = ('\''.*?'\'' | '"'.*?'"')
boolean     = ('true' | 'false')
regpattern  = '/'.*?'/i?x?'
null        = 'null'
index       = -?[0-9]+

jsonpath    = '$' operator*
childpath   = '@' operator*

operator    = (childname | childfilter | recursive) operator*

childname   = '.' (var_name | '*')
childfilter = '[' ('*' | namelist | indexlist | arrayslice | filterexpr) ']'
recursive   = '..' (var_name | childfilter | '*')

namelist    = var_name (',' (var_name | '\'' .*? '\'' | '"' .*? '"'))*
indexlist   = index (',' index)*
arrayslice  = index? ':' index? ':' index?
filterexpr  = '?(' ors ' | regpattern)'

ors         = ands (' ' ( 'or' | '\|\|' ) ' ' ands)*
ands        = expr (' ' ( 'and' | '&&' ) ' ' expr)*
expr        = ( 'not ' | '! ' )? (value | comp | in_array)
comp        = value ('==' | '!=' | '' | '=' | '=~') value
value       = (jsonpath | childpath | number | string | boolean | regpattern | null | length)
length      = (jsonpath | childpath) '.length'
in_array    = value 'in' '[' value (',' value)* ']'

```

¹`var_name`: the regex roughly translates to "any valid JavaScript variable name", plus some quirks such as names starting with numbers or containing dashes (`-`).

### Limitations on the specification:

[](#limitations-on-the-specification)

- The jsonpath inside *value* cannot contain `or`, `and` or any comparator.
- Jsonpaths in *value* return the first element of the set or `false` if no result.
- Boolean operations can't be grouped with parethesis.
- `and`s are run before `or`s. That means that `a and 1 = b or c != d` is the same as `(a and 1) or (c != d)`

**The `.length` operator** can be used to:

- Get the number of childs a node in the JsonObject has: `$..*[?(@.length > 3)]`
- Filter for nodes that have childs: `$..*[?(@.length)]`
- Or filter for nodes that don't have childs (leaves): `$..*[?(not @.length)]`
- Check the length of a string: `$.path.to[?(@.a.string.length > 10)]`
- Get the length of a string: `$.path.to.field.length`
- Get the length of an array: `$.path.to.array.length`
- Get the length of each array inside an array of arrays: `$.path.to.array[*].array[*].length`
- Get the length of each string inside an array of strings: `$.path.to.array[*].array[*].key.length`

**The comparators**:
`==`, `!=`, ``, `=` do what expected (compare by type and value).
`=~` is a regex comparator, matches the left operand with the pattern in the right operand. The value on the left must be a *string* and on the right *regpattern*. Other wise returns `false`.

JsonPath Example
================

[](#jsonpath-example)

Consider the following json:

```
{ "store": {
    "book": [
      { "category": "reference",
        "author": "Nigel Rees",
        "title": "Sayings of the Century",
        "price": 8.95,
        "available": true
      },
      { "category": "fiction",
        "author": "Evelyn Waugh",
        "title": "Sword of Honour",
        "price": 12.99,
        "available": false
      },
      { "category": "fiction",
        "author": "Herman Melville",
        "title": "Moby Dick",
        "isbn": "0-553-21311-3",
        "price": 8.99,
        "available": true
      },
      { "category": "fiction",
        "author": "J. R. R. Tolkien",
        "title": "The Lord of the Rings",
        "isbn": "0-395-19395-8",
        "price": 22.99,
        "available": false
      }
    ],
    "bicycle": {
      "color": "red",
      "price": 19.95,
      "available": true
    }
  },
  "authors": [
    "Nigel Rees",
    "Evelyn Waugh",
    "Herman Melville",
    "J. R. R. Tolkien"
  ]
}
```

JsonPathResult`$.store.bicycle.price`The price of the bicycle.`$.store.book[*]`All books.`$.store.book[1,3]`The second and fourth book.`$.store.book[1:3]`From the second book to the third.`$.store.book[:3]`From the first book to the third.`$.store.book[x:y:z]`Books from x to y with a step of z.`$..book[?(@.category == 'fiction')]`All books with category == 'fiction'.`$..*[?(@.available == true)].price`All prices of available products.`$..book[?(@.price < 10)].title`The title of all books with price lower than 10.`$..book[?(@.author==$.authors[3])]`All books by "J. R. R. Tolkien"`$[store]`The store.`$['store']`The store.`$..book[*][title, 'category', "author"]`title, category and author of all books.`$..book[?(@.author in [$.authors[0], $.authors[2]])]`All books by "Nigel Rees" or "Herman Melville".`$.store.book[?(@.category == 'fiction' and @.price < 10 or @.color == "red")].price`Books of fiction with a price lower than 10 or something with of color red. (`and` takes precedence to `or`)See more examples in the `./tests/Galbar/JsonPath` folder.

Test
====

[](#test)

To run tests, from the project root folder:
`php app/test.php  []`

If no json file is given it defaults to the json object described previously in this file.

For example:
`php app/test.php "$..*[?(@.category == 'fiction' and @.price < 10 or @.color == \"red\")].price"`
Result should be:
`[19.95,8.99]`

Ready to code
=============

[](#ready-to-code)

you can open the project in your browser and can start coding [![Gitpod ready-to-code](https://camo.githubusercontent.com/c01324668ea00cd2b02dc9fbf541676fb30543b69ef99a070d62a110917126d0/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f476974706f642d72656164792d2d746f2d2d636f64652d626c75653f6c6f676f3d676974706f64)](https://gitpod.io/#https://github.com/Galbar/JsonPath-PHP)

Docs
====

[](#docs)

To generate the docs, from the project root folder:
`php vendor/bin/sami.php update app/docgen.php`

###  Health Score

53

—

FairBetter than 97% of packages

Maintenance35

Infrequent updates — may be unmaintained

Popularity63

Solid adoption and visibility

Community40

Growing community involvement

Maturity66

Established project with proven stability

 Bus Factor1

Top contributor holds 59.3% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~182 days

Recently: every ~147 days

Total

16

Last Release

1170d ago

Major Versions

0.8 → 1.02017-09-13

1.3.1 → 2.02021-08-19

2.1 → 3.02023-03-05

PHP version history (2 changes)0.5.0PHP &gt;=5.3.3

1.0PHP &gt;=5.4

### Community

Maintainers

![](https://www.gravatar.com/avatar/ee3dcde63eb48e7ebbdc98931d75249ff5bba95b2bfc1c21cb642d222220e874?d=identicon)[Galbar](/maintainers/Galbar)

---

Top Contributors

[![Galbar](https://avatars.githubusercontent.com/u/3595851?v=4)](https://github.com/Galbar "Galbar (48 commits)")[![motanelu](https://avatars.githubusercontent.com/u/70403?v=4)](https://github.com/motanelu "motanelu (8 commits)")[![fayway](https://avatars.githubusercontent.com/u/1507839?v=4)](https://github.com/fayway "fayway (7 commits)")[![SergeyNikolaev](https://avatars.githubusercontent.com/u/5138660?v=4)](https://github.com/SergeyNikolaev "SergeyNikolaev (6 commits)")[![bwl21](https://avatars.githubusercontent.com/u/2022976?v=4)](https://github.com/bwl21 "bwl21 (3 commits)")[![TheDigitalOrchard](https://avatars.githubusercontent.com/u/3195423?v=4)](https://github.com/TheDigitalOrchard "TheDigitalOrchard (3 commits)")[![richardkeen](https://avatars.githubusercontent.com/u/23568?v=4)](https://github.com/richardkeen "richardkeen (2 commits)")[![lksnmnn](https://avatars.githubusercontent.com/u/4983285?v=4)](https://github.com/lksnmnn "lksnmnn (1 commits)")[![ruudk](https://avatars.githubusercontent.com/u/104180?v=4)](https://github.com/ruudk "ruudk (1 commits)")[![javibravo](https://avatars.githubusercontent.com/u/336993?v=4)](https://github.com/javibravo "javibravo (1 commits)")[![lucasangi](https://avatars.githubusercontent.com/u/31991195?v=4)](https://github.com/lucasangi "lucasangi (1 commits)")

---

Tags

json-objectsjsonpathphpjsonjsonpathpath

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/galbar-jsonpath/health.svg)

```
[![Health](https://phpackages.com/badges/galbar-jsonpath/health.svg)](https://phpackages.com/packages/galbar-jsonpath)
```

###  Alternatives

[mtdowling/jmespath.php

Declaratively specify how to extract elements from a JSON document

2.0k472.8M135](/packages/mtdowling-jmespathphp)[justinrainbow/json-schema

A library to validate a json schema.

3.6k316.9M612](/packages/justinrainbow-json-schema)[jms/serializer

Library for (de-)serializing data of any complexity; supports XML, and JSON.

2.3k135.8M851](/packages/jms-serializer)[jms/serializer-bundle

Allows you to easily serialize, and deserialize data of any complexity

1.8k89.3M627](/packages/jms-serializer-bundle)[colinodell/json5

UTF-8 compatible JSON5 parser for PHP

30422.2M45](/packages/colinodell-json5)[clue/ndjson-react

Streaming newline-delimited JSON (NDJSON) parser and encoder for ReactPHP.

15467.7M16](/packages/clue-ndjson-react)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
