|
| 1 | +JSONPath  |
| 2 | +============= |
| 3 | + |
| 4 | +This is a [JSONPath](http://goessner.net/articles/JsonPath/) implementation for PHP based on Stefan Goessner's JSONPath script. |
| 5 | + |
| 6 | +JSONPath is an XPath-like expression language for filtering, flattening and extracting data. |
| 7 | + |
| 8 | +This project aims to be a clean and simple implementation with the following goals: |
| 9 | + |
| 10 | + - Object-oriented code (should be easier to manage or extend in future) |
| 11 | + - Expressions are parsed into tokens using code inspired by the Doctrine Lexer. The tokens are cached internally to avoid re-parsing the expressions. |
| 12 | + - There is no `eval()` in use |
| 13 | + - Any combination of objects/arrays/ArrayAccess-objects can be used as the data input which is great if you're de-serializing JSON in to objects or if you want to process your own data structures. |
| 14 | + |
| 15 | +Installation |
| 16 | +--- |
| 17 | + |
| 18 | +**PHP 7.2+** |
| 19 | +```bash |
| 20 | +composer require softcreatr/jsonpath |
| 21 | +``` |
| 22 | +**PHP < 7.2** |
| 23 | + |
| 24 | +Support for PHP < 7.2 has been completely dropped. A legacy branch is maintained in the original repository in php-5.x and can be composer-installed as follows: `"flow/jsonpath": "dev-php-5.x"` |
| 25 | + |
| 26 | +JSONPath Examples |
| 27 | +--- |
| 28 | + |
| 29 | +JSONPath | Result |
| 30 | +--------------------------|------------------------------------- |
| 31 | +`$.store.books[*].author` | the authors of all books in the store |
| 32 | +`$..author` | all authors |
| 33 | +`$.store..price` | the price of everything in the store. |
| 34 | +`$..books[2]` | the third book |
| 35 | +`$..books[(@.length-1)]` | the last book in order. |
| 36 | +`$..books[-1:]` | the last book in order. |
| 37 | +`$..books[0,1]` | the first two books |
| 38 | +`$..books[:2]` | the first two books |
| 39 | +`$..books[::2]` | every second book starting from first one |
| 40 | +`$..books[1:6:3]` | every third book starting from 1 till 6 |
| 41 | +`$..books[?(@.isbn)]` | filter all books with isbn number |
| 42 | +`$..books[?(@.price<10)]` | filter all books cheapier than 10 |
| 43 | +`$..*` | all elements in the data (recursively extracted) |
| 44 | + |
| 45 | + |
| 46 | +Expression syntax |
| 47 | +--- |
| 48 | + |
| 49 | +Symbol | Description |
| 50 | +----------------------|------------------------- |
| 51 | +`$` | The root object/element (not strictly necessary) |
| 52 | +`@` | The current object/element |
| 53 | +`.` or `[]` | Child operator |
| 54 | +`..` | Recursive descent |
| 55 | +`*` | Wildcard. All child elements regardless their index. |
| 56 | +`[,]` | Array indices as a set |
| 57 | +`[start:end:step]` | Array slice operator borrowed from ES4/Python. |
| 58 | +`?()` | Filters a result set by a script expression |
| 59 | +`()` | Uses the result of a script expression as the index |
| 60 | + |
| 61 | +PHP Usage |
| 62 | +--- |
| 63 | + |
| 64 | +```php |
| 65 | +$data = ['people' => [['name' => 'Joe'], ['name' => 'Jane'], ['name' => 'John']]]; |
| 66 | +$result = (new JSONPath($data))->find('$.people.*.name'); // returns new JSONPath |
| 67 | +// $result[0] === 'Joe' |
| 68 | +// $result[1] === 'Jane' |
| 69 | +// $result[2] === 'John' |
| 70 | +``` |
| 71 | + |
| 72 | +### Magic method access |
| 73 | + |
| 74 | +The options flag `JSONPath::ALLOW_MAGIC` will instruct JSONPath when retrieving a value to first check if an object |
| 75 | +has a magic `__get()` method and will call this method if available. This feature is *iffy* and |
| 76 | +not very predictable as: |
| 77 | + |
| 78 | +- wildcard and recursive features will only look at public properties and can't smell which properties are magically accessible |
| 79 | +- there is no `property_exists` check for magic methods so an object with a magic `__get()` will always return `true` when checking |
| 80 | + if the property exists |
| 81 | +- any errors thrown or unpredictable behaviour caused by fetching via `__get()` is your own problem to deal with |
| 82 | + |
| 83 | +```php |
| 84 | +$jsonPath = new JSONPath($myObject, JSONPath::ALLOW_MAGIC); |
| 85 | +``` |
| 86 | + |
| 87 | +For more examples, check the JSONPathTest.php tests file. |
| 88 | + |
| 89 | +Script expressions |
| 90 | +------- |
| 91 | + |
| 92 | +Script expressions are not supported as the original author intended because: |
| 93 | + |
| 94 | +- This would only be achievable through `eval` (boo). |
| 95 | +- Using the script engine from different languages defeats the purpose of having a single expression evaluate the same way in different |
| 96 | + languages which seems like a bit of a flaw if you're creating an abstract expression syntax. |
| 97 | + |
| 98 | +So here are the types of query expressions that are supported: |
| 99 | + |
| 100 | + [?(@._KEY_ _OPERATOR_ _VALUE_)] // <, >, !=, and == |
| 101 | + Eg. |
| 102 | + [?(@.title == "A string")] // |
| 103 | + [?(@.title = "A string")] |
| 104 | + // A single equals is not an assignment but the SQL-style of '==' |
| 105 | + |
| 106 | +Known issues |
| 107 | +------ |
| 108 | + |
| 109 | +- This project has not implemented multiple string indexes eg. `$[name,year]` or `$["name","year"]`. I have no ETA on that feature and it would require some re-writing of the parser that uses a very basic regex implementation. |
| 110 | + |
| 111 | +Similar projects |
| 112 | +---------------- |
| 113 | + |
| 114 | +[FlowCommunications/JSONPath](https://github.com/FlowCommunications/JSONPath) is the predecessor of this library by Stephen Frank |
| 115 | + |
| 116 | +[Galbar/JsonPath-PHP](https://github.com/Galbar/JsonPath-PHP) is a PHP implementation that does a few things this project doesn't and is a strong alternative |
| 117 | + |
| 118 | +[JMESPath](https://github.com/jmespath) does similiar things, is full of features and has a PHP implementation |
| 119 | + |
| 120 | +The [Hash](http://book.cakephp.org/2.0/en/core-utility-libraries/hash.html) utility from CakePHP does some similar things |
| 121 | + |
| 122 | +The original JsonPath implementations is available at [http://code.google.com/p/jsonpath]() and re-hosted for composer |
| 123 | +here [Peekmo/JsonPath](https://github.com/Peekmo/JsonPath). |
| 124 | + |
| 125 | +[ObjectPath](http://objectpath.org) ([https://github.com/adriank/ObjectPath]()) appears to be a Python/JS implementation with a new name and extra features. |
| 126 | + |
| 127 | +Changelog |
| 128 | +--------- |
| 129 | + |
| 130 | +### 0.6.0 |
| 131 | + - Dropped support for PHP < 7.2 |
| 132 | + - Switched from (broken) PSR-0 to PSR-4 |
| 133 | + - Updated PHPUnit to 8.5 / 9.4 |
| 134 | + - Updated tests |
| 135 | + - Added missing PHPDoc blocks |
| 136 | + - Added return type hints |
| 137 | + - Moved from Travis to GitHub actions |
| 138 | + |
| 139 | +### 0.5.0 |
| 140 | + - Fixed the slice notation (eg. [0:2:5] etc.). **Breaks code relying on the broken implementation** |
| 141 | + |
| 142 | +### 0.3.0 |
| 143 | + - Added JSONPathToken class as value object |
| 144 | + - Lexer clean up and refactor |
| 145 | + - Updated the lexing and filtering of the recursive token ("..") to allow for a combination of recursion |
| 146 | + and filters, eg. $..[?(@.type == 'suburb')].name |
| 147 | + |
| 148 | +### 0.2.1 - 0.2.5 |
| 149 | + - Various bug fixes and clean up |
| 150 | + |
| 151 | +### 0.2.0 |
| 152 | + - Added a heap of array access features for more creative iterating and chaining possibilities |
| 153 | + |
| 154 | +### 0.1.x |
| 155 | + - Init |
| 156 | + |
| 157 | +License |
| 158 | +--------- |
| 159 | + |
| 160 | +[MIT](LICENSE) |
0 commit comments