././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1705001033.7198036 jsonpath-ng-1.6.1/0000775000175100017510000000000014550040112013033 5ustar00mmiormmior././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1689268185.0 jsonpath-ng-1.6.1/LICENSE0000664000175100017510000002613614454027731014067 0ustar00mmiormmior Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1695653930.0 jsonpath-ng-1.6.1/MANIFEST.in0000664000175100017510000000006414504320052014574 0ustar00mmiormmiorrecursive-include tests *.json *.py include LICENSE ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1705001033.7198036 jsonpath-ng-1.6.1/PKG-INFO0000664000175100017510000004320514550040112014134 0ustar00mmiormmiorMetadata-Version: 2.1 Name: jsonpath-ng Version: 1.6.1 Summary: A final implementation of JSONPath for Python that aims to be standard compliant, including arithmetic and binary comparison operators and providing clear AST for metaprogramming. Home-page: https://github.com/h2non/jsonpath-ng Author: Tomas Aparicio Author-email: tomas@aparicio.me License: Apache 2.0 Classifier: Development Status :: 5 - Production/Stable Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: Apache Software License Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: 3.7 Classifier: Programming Language :: Python :: 3.8 Classifier: Programming Language :: Python :: 3.9 Classifier: Programming Language :: Python :: 3.10 Classifier: Programming Language :: Python :: 3.11 Classifier: Programming Language :: Python :: 3.12 License-File: LICENSE Python JSONPath Next-Generation |Build Status| |PyPI| ===================================================== A final implementation of JSONPath for Python that aims to be standard compliant, including arithmetic and binary comparison operators, as defined in the original `JSONPath proposal`_. This packages merges both `jsonpath-rw`_ and `jsonpath-rw-ext`_ and provides several AST API enhancements, such as the ability to update or remove nodes in the tree. About ----- This library provides a robust and significantly extended implementation of JSONPath for Python. It is tested with CPython 3.7 and higher. This library differs from other JSONPath implementations in that it is a full *language* implementation, meaning the JSONPath expressions are first class objects, easy to analyze, transform, parse, print, and extend. Quick Start ----------- To install, use pip: .. code:: bash $ pip install --upgrade jsonpath-ng Usage ----- Basic examples: .. code:: python $ python >>> from jsonpath_ng import jsonpath, parse # A robust parser, not just a regex. (Makes powerful extensions possible; see below) >>> jsonpath_expr = parse('foo[*].baz') # Extracting values is easy >>> [match.value for match in jsonpath_expr.find({'foo': [{'baz': 1}, {'baz': 2}]})] [1, 2] # Matches remember where they came from >>> [str(match.full_path) for match in jsonpath_expr.find({'foo': [{'baz': 1}, {'baz': 2}]})] ['foo.[0].baz', 'foo.[1].baz'] # Modifying values matching the path >>> jsonpath_expr.update( {'foo': [{'baz': 1}, {'baz': 2}]}, 3) {'foo': [{'baz': 3}, {'baz': 3}]} # Modifying one of the values matching the path >>> matches = jsonpath_expr.find({'foo': [{'baz': 1}, {'baz': 2}]}) >>> matches[0].full_path.update( {'foo': [{'baz': 1}, {'baz': 2}]}, 3) {'foo': [{'baz': 3}, {'baz': 2}]} # Removing all values matching a path >>> jsonpath_expr.filter(lambda d: True, {'foo': [{'baz': 1}, {'baz': 2}]}) {'foo': [{}, {}]} # Removing values containing particular data matching path >>> jsonpath_expr.filter(lambda d: d == 2, {'foo': [{'baz': 1}, {'baz': 2}]}) {'foo': [{'baz': 1}, {}]} # And this can be useful for automatically providing ids for bits of data that do not have them (currently a global switch) >>> jsonpath.auto_id_field = 'id' >>> [match.value for match in parse('foo[*].id').find({'foo': [{'id': 'bizzle'}, {'baz': 3}]})] ['foo.bizzle', 'foo.[1]'] # A handy extension: named operators like `parent` >>> [match.value for match in parse('a.*.b.`parent`.c').find({'a': {'x': {'b': 1, 'c': 'number one'}, 'y': {'b': 2, 'c': 'number two'}}})] ['number two', 'number one'] # You can also build expressions directly quite easily >>> from jsonpath_ng.jsonpath import Fields >>> from jsonpath_ng.jsonpath import Slice >>> jsonpath_expr_direct = Fields('foo').child(Slice('*')).child(Fields('baz')) # This is equivalent Using the extended parser: .. code:: python $ python >>> from jsonpath_ng.ext import parse # A robust parser, not just a regex. (Makes powerful extensions possible; see below) >>> jsonpath_expr = parse('foo[*].baz') JSONPath Syntax --------------- The JSONPath syntax supported by this library includes some additional features and omits some problematic features (those that make it unportable). In particular, some new operators such as ``|`` and ``where`` are available, and parentheses are used for grouping not for callbacks into Python, since with these changes the language is not trivially associative. Also, fields may be quoted whether or not they are contained in brackets. Atomic expressions: +-----------------------+---------------------------------------------------------------------------------------------+ | Syntax | Meaning | +=======================+=============================================================================================+ | ``$`` | The root object | +-----------------------+---------------------------------------------------------------------------------------------+ | ```this``` | The "current" object. | +-----------------------+---------------------------------------------------------------------------------------------+ | ```foo``` | More generally, this syntax allows "named operators" to extend JSONPath is arbitrary ways | +-----------------------+---------------------------------------------------------------------------------------------+ | *field* | Specified field(s), described below | +-----------------------+---------------------------------------------------------------------------------------------+ | ``[`` *field* ``]`` | Same as *field* | +-----------------------+---------------------------------------------------------------------------------------------+ | ``[`` *idx* ``]`` | Array access, described below (this is always unambiguous with field access) | +-----------------------+---------------------------------------------------------------------------------------------+ Jsonpath operators: +-------------------------------------+------------------------------------------------------------------------------------+ | Syntax | Meaning | +=====================================+====================================================================================+ | *jsonpath1* ``.`` *jsonpath2* | All nodes matched by *jsonpath2* starting at any node matching *jsonpath1* | +-------------------------------------+------------------------------------------------------------------------------------+ | *jsonpath* ``[`` *whatever* ``]`` | Same as *jsonpath*\ ``.``\ *whatever* | +-------------------------------------+------------------------------------------------------------------------------------+ | *jsonpath1* ``..`` *jsonpath2* | All nodes matched by *jsonpath2* that descend from any node matching *jsonpath1* | +-------------------------------------+------------------------------------------------------------------------------------+ | *jsonpath1* ``where`` *jsonpath2* | Any nodes matching *jsonpath1* with a child matching *jsonpath2* | +-------------------------------------+------------------------------------------------------------------------------------+ | *jsonpath1* ``|`` *jsonpath2* | Any nodes matching the union of *jsonpath1* and *jsonpath2* | +-------------------------------------+------------------------------------------------------------------------------------+ Field specifiers ( *field* ): +-------------------------+-------------------------------------------------------------------------------------+ | Syntax | Meaning | +=========================+=====================================================================================+ | ``fieldname`` | the field ``fieldname`` (from the "current" object) | +-------------------------+-------------------------------------------------------------------------------------+ | ``"fieldname"`` | same as above, for allowing special characters in the fieldname | +-------------------------+-------------------------------------------------------------------------------------+ | ``'fieldname'`` | ditto | +-------------------------+-------------------------------------------------------------------------------------+ | ``*`` | any field | +-------------------------+-------------------------------------------------------------------------------------+ | *field* ``,`` *field* | either of the named fields (you can always build equivalent jsonpath using ``|``) | +-------------------------+-------------------------------------------------------------------------------------+ Array specifiers ( *idx* ): +-----------------------------------------+---------------------------------------------------------------------------------------+ | Syntax | Meaning | +=========================================+=======================================================================================+ | ``[``\ *n*\ ``]`` | array index (may be comma-separated list) | +-----------------------------------------+---------------------------------------------------------------------------------------+ | ``[``\ *start*\ ``?:``\ *end*\ ``?]`` | array slicing (note that *step* is unimplemented only due to lack of need thus far) | +-----------------------------------------+---------------------------------------------------------------------------------------+ | ``[*]`` | any array index | +-----------------------------------------+---------------------------------------------------------------------------------------+ Programmatic JSONPath --------------------- If you are programming in Python and would like a more robust way to create JSONPath expressions that does not depend on a parser, it is very easy to do so directly, and here are some examples: - ``Root()`` - ``Slice(start=0, end=None, step=None)`` - ``Fields('foo', 'bar')`` - ``Index(42)`` - ``Child(Fields('foo'), Index(42))`` - ``Where(Slice(), Fields('subfield'))`` - ``Descendants(jsonpath, jsonpath)`` Extras ------ - *Path data*: The result of ``JsonPath.find`` provide detailed context and path data so it is easy to traverse to parent objects, print full paths to pieces of data, and generate automatic ids. - *Automatic Ids*: If you set ``jsonpath_ng.auto_id_field`` to a value other than None, then for any piece of data missing that field, it will be replaced by the JSONPath to it, giving automatic unique ids to any piece of data. These ids will take into account any ids already present as well. - *Named operators*: Instead of using ``@`` to reference the current object, this library uses ```this```. In general, any string contained in backquotes can be made to be a new operator, currently by extending the library. Extensions ---------- To use the extensions below you must import from `jsonpath_ng.ext`. +--------------+-----------------------------------------------+ | name | Example | +==============+===============================================+ | len | - ``$.objects.`len``` | +--------------+-----------------------------------------------+ | sub | - ``$.field.`sub(/foo\\\\+(.*)/, \\\\1)``` | | | - ``$.field.`sub(/regex/, replacement)``` | +--------------+-----------------------------------------------+ | split | - ``$.field.`split(+, 2, -1)``` | | | - ``$.field.`split(sep, segement, maxsplit)```| +--------------+-----------------------------------------------+ | sorted | - ``$.objects.`sorted``` | | | - ``$.objects[\\some_field]`` | | | - ``$.objects[\\some_field,/other_field]`` | +--------------+-----------------------------------------------+ | filter | - ``$.objects[?(@some_field > 5)]`` | | | - ``$.objects[?some_field = "foobar"]`` | | | - ``$.objects[?some_field =~ "foobar"]`` | | | - ``$.objects[?some_field > 5 & other < 2]`` | | | | | | Supported operators: | | | - Equality: ==, =, != | | | - Comparison: >, >=, <, <= | | | - Regex match: =~ | | | | | | Combine multiple criteria with '&'. | | | | | | Properties can only be compared to static | | | values. | +--------------+-----------------------------------------------+ | arithmetic | - ``$.foo + "_" + $.bar`` | | (-+*/) | - ``$.foo * 12`` | | | - ``$.objects[*].cow + $.objects[*].cat`` | +--------------+-----------------------------------------------+ About arithmetic and string --------------------------- Operations are done with python operators and allows types that python allows, and return [] if the operation can be done due to incompatible types. When operators are used, a jsonpath must be be fully defined otherwise jsonpath-rw-ext can't known if the expression is a string or a jsonpath field, in this case it will choice string as type. Example with data:: { 'cow': 'foo', 'fish': 'bar' } | ``cow + fish`` returns ``cowfish`` | ``$.cow + $.fish`` returns ``foobar`` | ``$.cow + "_" + $.fish`` returns ``foo_bar`` | ``$.cow + "_" + fish`` returns ``foo_fish`` About arithmetic and list ------------------------- Arithmetic can be used against two lists if they have the same size. Example with data:: {'objects': [ {'cow': 2, 'cat': 3}, {'cow': 4, 'cat': 6} ]} | ``$.objects[\*].cow + $.objects[\*].cat`` returns ``[6, 9]`` More to explore --------------- There are way too many JSONPath implementations out there to discuss. Some are robust, some are toy projects that still work fine, some are exercises. There will undoubtedly be many more. This one is made for use in released, maintained code, and in particular for programmatic access to the abstract syntax and extension. But JSONPath at its simplest just isn't that complicated, so you can probably use any of them successfully. Why not this one? The original proposal, as far as I know: - `JSONPath - XPath for JSON `__ by Stefan Goessner. Other examples -------------- Loading json data from file .. code:: python import json d = json.loads('{"foo": [{"baz": 1}, {"baz": 2}]}') # or with open('myfile.json') as f: d = json.load(f) Special note about PLY and docstrings ------------------------------------- The main parsing toolkit underlying this library, `PLY `__, does not work with docstrings removed. For example, ``PYTHONOPTIMIZE=2`` and ``python -OO`` will both cause a failure. Contributors ------------ This package is authored and maintained by: - `Kenn Knowles `__ (`@kennknowles `__) - `Tomas Aparicio ` with the help of patches submitted by `these contributors `__. Copyright and License --------------------- Copyright 2013 - Kenneth Knowles Copyright 2017 - Tomas Aparicio Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at :: http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. .. _`JSONPath proposal`: http://goessner.net/articles/JsonPath/ .. _`jsonpath-rw`: https://github.com/kennknowles/python-jsonpath-rw .. _`jsonpath-rw-ext`: https://pypi.python.org/pypi/jsonpath-rw-ext/ .. |PyPi downloads| image:: https://pypip.in/d/jsonpath-ng/badge.png :target: https://pypi.python.org/pypi/jsonpath-ng .. |Build Status| image:: https://github.com/h2non/jsonpath-ng/actions/workflows/ci.yml/badge.svg :target: https://github.com/h2non/jsonpath-ng/actions/workflows/ci.yml .. |PyPI| image:: https://img.shields.io/pypi/v/jsonpath-ng.svg?maxAge=2592000?style=flat-square :target: https://pypi.python.org/pypi/jsonpath-ng ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1699968179.0 jsonpath-ng-1.6.1/README.rst0000664000175100017510000004137514524672263014557 0ustar00mmiormmiorPython JSONPath Next-Generation |Build Status| |PyPI| ===================================================== A final implementation of JSONPath for Python that aims to be standard compliant, including arithmetic and binary comparison operators, as defined in the original `JSONPath proposal`_. This packages merges both `jsonpath-rw`_ and `jsonpath-rw-ext`_ and provides several AST API enhancements, such as the ability to update or remove nodes in the tree. About ----- This library provides a robust and significantly extended implementation of JSONPath for Python. It is tested with CPython 3.7 and higher. This library differs from other JSONPath implementations in that it is a full *language* implementation, meaning the JSONPath expressions are first class objects, easy to analyze, transform, parse, print, and extend. Quick Start ----------- To install, use pip: .. code:: bash $ pip install --upgrade jsonpath-ng Usage ----- Basic examples: .. code:: python $ python >>> from jsonpath_ng import jsonpath, parse # A robust parser, not just a regex. (Makes powerful extensions possible; see below) >>> jsonpath_expr = parse('foo[*].baz') # Extracting values is easy >>> [match.value for match in jsonpath_expr.find({'foo': [{'baz': 1}, {'baz': 2}]})] [1, 2] # Matches remember where they came from >>> [str(match.full_path) for match in jsonpath_expr.find({'foo': [{'baz': 1}, {'baz': 2}]})] ['foo.[0].baz', 'foo.[1].baz'] # Modifying values matching the path >>> jsonpath_expr.update( {'foo': [{'baz': 1}, {'baz': 2}]}, 3) {'foo': [{'baz': 3}, {'baz': 3}]} # Modifying one of the values matching the path >>> matches = jsonpath_expr.find({'foo': [{'baz': 1}, {'baz': 2}]}) >>> matches[0].full_path.update( {'foo': [{'baz': 1}, {'baz': 2}]}, 3) {'foo': [{'baz': 3}, {'baz': 2}]} # Removing all values matching a path >>> jsonpath_expr.filter(lambda d: True, {'foo': [{'baz': 1}, {'baz': 2}]}) {'foo': [{}, {}]} # Removing values containing particular data matching path >>> jsonpath_expr.filter(lambda d: d == 2, {'foo': [{'baz': 1}, {'baz': 2}]}) {'foo': [{'baz': 1}, {}]} # And this can be useful for automatically providing ids for bits of data that do not have them (currently a global switch) >>> jsonpath.auto_id_field = 'id' >>> [match.value for match in parse('foo[*].id').find({'foo': [{'id': 'bizzle'}, {'baz': 3}]})] ['foo.bizzle', 'foo.[1]'] # A handy extension: named operators like `parent` >>> [match.value for match in parse('a.*.b.`parent`.c').find({'a': {'x': {'b': 1, 'c': 'number one'}, 'y': {'b': 2, 'c': 'number two'}}})] ['number two', 'number one'] # You can also build expressions directly quite easily >>> from jsonpath_ng.jsonpath import Fields >>> from jsonpath_ng.jsonpath import Slice >>> jsonpath_expr_direct = Fields('foo').child(Slice('*')).child(Fields('baz')) # This is equivalent Using the extended parser: .. code:: python $ python >>> from jsonpath_ng.ext import parse # A robust parser, not just a regex. (Makes powerful extensions possible; see below) >>> jsonpath_expr = parse('foo[*].baz') JSONPath Syntax --------------- The JSONPath syntax supported by this library includes some additional features and omits some problematic features (those that make it unportable). In particular, some new operators such as ``|`` and ``where`` are available, and parentheses are used for grouping not for callbacks into Python, since with these changes the language is not trivially associative. Also, fields may be quoted whether or not they are contained in brackets. Atomic expressions: +-----------------------+---------------------------------------------------------------------------------------------+ | Syntax | Meaning | +=======================+=============================================================================================+ | ``$`` | The root object | +-----------------------+---------------------------------------------------------------------------------------------+ | ```this``` | The "current" object. | +-----------------------+---------------------------------------------------------------------------------------------+ | ```foo``` | More generally, this syntax allows "named operators" to extend JSONPath is arbitrary ways | +-----------------------+---------------------------------------------------------------------------------------------+ | *field* | Specified field(s), described below | +-----------------------+---------------------------------------------------------------------------------------------+ | ``[`` *field* ``]`` | Same as *field* | +-----------------------+---------------------------------------------------------------------------------------------+ | ``[`` *idx* ``]`` | Array access, described below (this is always unambiguous with field access) | +-----------------------+---------------------------------------------------------------------------------------------+ Jsonpath operators: +-------------------------------------+------------------------------------------------------------------------------------+ | Syntax | Meaning | +=====================================+====================================================================================+ | *jsonpath1* ``.`` *jsonpath2* | All nodes matched by *jsonpath2* starting at any node matching *jsonpath1* | +-------------------------------------+------------------------------------------------------------------------------------+ | *jsonpath* ``[`` *whatever* ``]`` | Same as *jsonpath*\ ``.``\ *whatever* | +-------------------------------------+------------------------------------------------------------------------------------+ | *jsonpath1* ``..`` *jsonpath2* | All nodes matched by *jsonpath2* that descend from any node matching *jsonpath1* | +-------------------------------------+------------------------------------------------------------------------------------+ | *jsonpath1* ``where`` *jsonpath2* | Any nodes matching *jsonpath1* with a child matching *jsonpath2* | +-------------------------------------+------------------------------------------------------------------------------------+ | *jsonpath1* ``|`` *jsonpath2* | Any nodes matching the union of *jsonpath1* and *jsonpath2* | +-------------------------------------+------------------------------------------------------------------------------------+ Field specifiers ( *field* ): +-------------------------+-------------------------------------------------------------------------------------+ | Syntax | Meaning | +=========================+=====================================================================================+ | ``fieldname`` | the field ``fieldname`` (from the "current" object) | +-------------------------+-------------------------------------------------------------------------------------+ | ``"fieldname"`` | same as above, for allowing special characters in the fieldname | +-------------------------+-------------------------------------------------------------------------------------+ | ``'fieldname'`` | ditto | +-------------------------+-------------------------------------------------------------------------------------+ | ``*`` | any field | +-------------------------+-------------------------------------------------------------------------------------+ | *field* ``,`` *field* | either of the named fields (you can always build equivalent jsonpath using ``|``) | +-------------------------+-------------------------------------------------------------------------------------+ Array specifiers ( *idx* ): +-----------------------------------------+---------------------------------------------------------------------------------------+ | Syntax | Meaning | +=========================================+=======================================================================================+ | ``[``\ *n*\ ``]`` | array index (may be comma-separated list) | +-----------------------------------------+---------------------------------------------------------------------------------------+ | ``[``\ *start*\ ``?:``\ *end*\ ``?]`` | array slicing (note that *step* is unimplemented only due to lack of need thus far) | +-----------------------------------------+---------------------------------------------------------------------------------------+ | ``[*]`` | any array index | +-----------------------------------------+---------------------------------------------------------------------------------------+ Programmatic JSONPath --------------------- If you are programming in Python and would like a more robust way to create JSONPath expressions that does not depend on a parser, it is very easy to do so directly, and here are some examples: - ``Root()`` - ``Slice(start=0, end=None, step=None)`` - ``Fields('foo', 'bar')`` - ``Index(42)`` - ``Child(Fields('foo'), Index(42))`` - ``Where(Slice(), Fields('subfield'))`` - ``Descendants(jsonpath, jsonpath)`` Extras ------ - *Path data*: The result of ``JsonPath.find`` provide detailed context and path data so it is easy to traverse to parent objects, print full paths to pieces of data, and generate automatic ids. - *Automatic Ids*: If you set ``jsonpath_ng.auto_id_field`` to a value other than None, then for any piece of data missing that field, it will be replaced by the JSONPath to it, giving automatic unique ids to any piece of data. These ids will take into account any ids already present as well. - *Named operators*: Instead of using ``@`` to reference the current object, this library uses ```this```. In general, any string contained in backquotes can be made to be a new operator, currently by extending the library. Extensions ---------- To use the extensions below you must import from `jsonpath_ng.ext`. +--------------+-----------------------------------------------+ | name | Example | +==============+===============================================+ | len | - ``$.objects.`len``` | +--------------+-----------------------------------------------+ | sub | - ``$.field.`sub(/foo\\\\+(.*)/, \\\\1)``` | | | - ``$.field.`sub(/regex/, replacement)``` | +--------------+-----------------------------------------------+ | split | - ``$.field.`split(+, 2, -1)``` | | | - ``$.field.`split(sep, segement, maxsplit)```| +--------------+-----------------------------------------------+ | sorted | - ``$.objects.`sorted``` | | | - ``$.objects[\\some_field]`` | | | - ``$.objects[\\some_field,/other_field]`` | +--------------+-----------------------------------------------+ | filter | - ``$.objects[?(@some_field > 5)]`` | | | - ``$.objects[?some_field = "foobar"]`` | | | - ``$.objects[?some_field =~ "foobar"]`` | | | - ``$.objects[?some_field > 5 & other < 2]`` | | | | | | Supported operators: | | | - Equality: ==, =, != | | | - Comparison: >, >=, <, <= | | | - Regex match: =~ | | | | | | Combine multiple criteria with '&'. | | | | | | Properties can only be compared to static | | | values. | +--------------+-----------------------------------------------+ | arithmetic | - ``$.foo + "_" + $.bar`` | | (-+*/) | - ``$.foo * 12`` | | | - ``$.objects[*].cow + $.objects[*].cat`` | +--------------+-----------------------------------------------+ About arithmetic and string --------------------------- Operations are done with python operators and allows types that python allows, and return [] if the operation can be done due to incompatible types. When operators are used, a jsonpath must be be fully defined otherwise jsonpath-rw-ext can't known if the expression is a string or a jsonpath field, in this case it will choice string as type. Example with data:: { 'cow': 'foo', 'fish': 'bar' } | ``cow + fish`` returns ``cowfish`` | ``$.cow + $.fish`` returns ``foobar`` | ``$.cow + "_" + $.fish`` returns ``foo_bar`` | ``$.cow + "_" + fish`` returns ``foo_fish`` About arithmetic and list ------------------------- Arithmetic can be used against two lists if they have the same size. Example with data:: {'objects': [ {'cow': 2, 'cat': 3}, {'cow': 4, 'cat': 6} ]} | ``$.objects[\*].cow + $.objects[\*].cat`` returns ``[6, 9]`` More to explore --------------- There are way too many JSONPath implementations out there to discuss. Some are robust, some are toy projects that still work fine, some are exercises. There will undoubtedly be many more. This one is made for use in released, maintained code, and in particular for programmatic access to the abstract syntax and extension. But JSONPath at its simplest just isn't that complicated, so you can probably use any of them successfully. Why not this one? The original proposal, as far as I know: - `JSONPath - XPath for JSON `__ by Stefan Goessner. Other examples -------------- Loading json data from file .. code:: python import json d = json.loads('{"foo": [{"baz": 1}, {"baz": 2}]}') # or with open('myfile.json') as f: d = json.load(f) Special note about PLY and docstrings ------------------------------------- The main parsing toolkit underlying this library, `PLY `__, does not work with docstrings removed. For example, ``PYTHONOPTIMIZE=2`` and ``python -OO`` will both cause a failure. Contributors ------------ This package is authored and maintained by: - `Kenn Knowles `__ (`@kennknowles `__) - `Tomas Aparicio ` with the help of patches submitted by `these contributors `__. Copyright and License --------------------- Copyright 2013 - Kenneth Knowles Copyright 2017 - Tomas Aparicio Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at :: http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. .. _`JSONPath proposal`: http://goessner.net/articles/JsonPath/ .. _`jsonpath-rw`: https://github.com/kennknowles/python-jsonpath-rw .. _`jsonpath-rw-ext`: https://pypi.python.org/pypi/jsonpath-rw-ext/ .. |PyPi downloads| image:: https://pypip.in/d/jsonpath-ng/badge.png :target: https://pypi.python.org/pypi/jsonpath-ng .. |Build Status| image:: https://github.com/h2non/jsonpath-ng/actions/workflows/ci.yml/badge.svg :target: https://github.com/h2non/jsonpath-ng/actions/workflows/ci.yml .. |PyPI| image:: https://img.shields.io/pypi/v/jsonpath-ng.svg?maxAge=2592000?style=flat-square :target: https://pypi.python.org/pypi/jsonpath-ng ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1705001033.7198036 jsonpath-ng-1.6.1/jsonpath_ng/0000775000175100017510000000000014550040112015345 5ustar00mmiormmior././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1705000706.0 jsonpath-ng-1.6.1/jsonpath_ng/__init__.py0000664000175100017510000000016414550037402017467 0ustar00mmiormmiorfrom .jsonpath import * # noqa from .parser import parse # noqa # Current package version __version__ = '1.6.1' ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1705001033.7198036 jsonpath-ng-1.6.1/jsonpath_ng/bin/0000775000175100017510000000000014550040112016115 5ustar00mmiormmior././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1689268185.0 jsonpath-ng-1.6.1/jsonpath_ng/bin/__init__.py0000664000175100017510000000000014454027731020233 0ustar00mmiormmior././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1699968179.0 jsonpath-ng-1.6.1/jsonpath_ng/bin/jsonpath.py0000775000175100017510000000401114524672263020337 0ustar00mmiormmior#!/usr/bin/python # encoding: utf-8 # Copyright © 2012 Felix Richter # This work is free. You can redistribute it and/or modify it under the # terms of the Do What The Fuck You Want To Public License, Version 2, # as published by Sam Hocevar. See the COPYING file for more details. # Standard Library imports import json import sys import glob import argparse # JsonPath-RW imports from jsonpath_ng import parse def find_matches_for_file(expr, f): return expr.find(json.load(f)) def print_matches(matches): print('\n'.join(['{0}'.format(match.value) for match in matches])) def main(*argv): parser = argparse.ArgumentParser( description='Search JSON files (or stdin) according to a JSONPath expression.', formatter_class=argparse.RawTextHelpFormatter, epilog=""" Quick JSONPath reference (see more at https://github.com/kennknowles/python-jsonpath-rw) atomics: $ - root object `this` - current object operators: path1.path2 - same as xpath / path1|path2 - union path1..path2 - somewhere in between fields: fieldname - field with name * - any field [_start_?:_end_?] - array slice [*] - any array index """) parser.add_argument('expression', help='A JSONPath expression.') parser.add_argument('files', metavar='file', nargs='*', help='Files to search (if none, searches stdin)') args = parser.parse_args(argv[1:]) expr = parse(args.expression) glob_patterns = args.files if len(glob_patterns) == 0: # stdin mode print_matches(find_matches_for_file(expr, sys.stdin)) else: # file paths mode for pattern in glob_patterns: for filename in glob.glob(pattern): with open(filename) as f: print_matches(find_matches_for_file(expr, f)) def entry_point(): main(*sys.argv) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1689268185.0 jsonpath-ng-1.6.1/jsonpath_ng/exceptions.py0000664000175100017510000000022214454027731020113 0ustar00mmiormmiorclass JSONPathError(Exception): pass class JsonPathLexerError(JSONPathError): pass class JsonPathParserError(JSONPathError): pass ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1705001033.7198036 jsonpath-ng-1.6.1/jsonpath_ng/ext/0000775000175100017510000000000014550040112016145 5ustar00mmiormmior././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1689268185.0 jsonpath-ng-1.6.1/jsonpath_ng/ext/__init__.py0000664000175100017510000000113514454027731020275 0ustar00mmiormmior# -*- coding: utf-8 -*- # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from .parser import parse # noqa ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1695646157.0 jsonpath-ng-1.6.1/jsonpath_ng/ext/arithmetic.py0000664000175100017510000000451514504300715020664 0ustar00mmiormmior# # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import operator from .. import JSONPath, DatumInContext OPERATOR_MAP = { '+': operator.add, '-': operator.sub, '*': operator.mul, '/': operator.truediv, } class Operation(JSONPath): def __init__(self, left, op, right): self.left = left self.op = OPERATOR_MAP[op] self.right = right def find(self, datum): result = [] if (isinstance(self.left, JSONPath) and isinstance(self.right, JSONPath)): left = self.left.find(datum) right = self.right.find(datum) if left and right and len(left) == len(right): for l, r in zip(left, right): try: result.append(self.op(l.value, r.value)) except TypeError: return [] else: return [] elif isinstance(self.left, JSONPath): left = self.left.find(datum) for l in left: try: result.append(self.op(l.value, self.right)) except TypeError: return [] elif isinstance(self.right, JSONPath): right = self.right.find(datum) for r in right: try: result.append(self.op(self.left, r.value)) except TypeError: return [] else: try: result.append(self.op(self.left, self.right)) except TypeError: return [] return [DatumInContext.wrap(r) for r in result] def __repr__(self): return '%s(%r%s%r)' % (self.__class__.__name__, self.left, self.op, self.right) def __str__(self): return '%s%s%s' % (self.left, self.op, self.right) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1695653930.0 jsonpath-ng-1.6.1/jsonpath_ng/ext/filter.py0000664000175100017510000001033014504320052020004 0ustar00mmiormmior# # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import operator import re from .. import JSONPath, DatumInContext, Index OPERATOR_MAP = { '!=': operator.ne, '==': operator.eq, '=': operator.eq, '<=': operator.le, '<': operator.lt, '>=': operator.ge, '>': operator.gt, '=~': lambda a, b: True if isinstance(a, str) and re.search(b, a) else False, } class Filter(JSONPath): """The JSONQuery filter""" def __init__(self, expressions): self.expressions = expressions def find(self, datum): if not self.expressions: return datum datum = DatumInContext.wrap(datum) if isinstance(datum.value, dict): datum.value = list(datum.value.values()) if not isinstance(datum.value, list): return [] return [DatumInContext(datum.value[i], path=Index(i), context=datum) for i in range(0, len(datum.value)) if (len(self.expressions) == len(list(filter(lambda x: x.find(datum.value[i]), self.expressions))))] def filter(self, fn, data): # NOTE: We reverse the order just to make sure the indexes are preserved upon # removal. for datum in reversed(self.find(data)): index_obj = datum.path if isinstance(data, dict): index_obj.index = list(data)[index_obj.index] index_obj.filter(fn, data) return data def update(self, data, val): if type(data) is list: for index, item in enumerate(data): shouldUpdate = len(self.expressions) == len(list(filter(lambda x: x.find(item), self.expressions))) if shouldUpdate: if hasattr(val, '__call__'): val.__call__(data[index], data, index) else: data[index] = val return data def __repr__(self): return '%s(%r)' % (self.__class__.__name__, self.expressions) def __str__(self): return '[?%s]' % self.expressions def __eq__(self, other): return (isinstance(other, Filter) and self.expressions == other.expressions) class Expression(JSONPath): """The JSONQuery expression""" def __init__(self, target, op, value): self.target = target self.op = op self.value = value def find(self, datum): datum = self.target.find(DatumInContext.wrap(datum)) if not datum: return [] if self.op is None: return datum found = [] for data in datum: value = data.value if isinstance(self.value, int): try: value = int(value) except ValueError: continue elif isinstance(self.value, bool): try: value = bool(value) except ValueError: continue if OPERATOR_MAP[self.op](value, self.value): found.append(data) return found def __eq__(self, other): return (isinstance(other, Expression) and self.target == other.target and self.op == other.op and self.value == other.value) def __repr__(self): if self.op is None: return '%s(%r)' % (self.__class__.__name__, self.target) else: return '%s(%r %s %r)' % (self.__class__.__name__, self.target, self.op, self.value) def __str__(self): if self.op is None: return '%s' % self.target else: return '%s %s %s' % (self.target, self.op, self.value) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1695655571.0 jsonpath-ng-1.6.1/jsonpath_ng/ext/iterable.py0000664000175100017510000000714014504323223020316 0ustar00mmiormmior# # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import functools from .. import This, DatumInContext, JSONPath class SortedThis(This): """The JSONPath referring to the sorted version of the current object. Concrete syntax is '`sorted`' or [\\field,/field]. """ def __init__(self, expressions=None): self.expressions = expressions def _compare(self, left, right): left = DatumInContext.wrap(left) right = DatumInContext.wrap(right) for expr in self.expressions: field, reverse = expr l_datum = field.find(left) r_datum = field.find(right) if (not l_datum or not r_datum or len(l_datum) > 1 or len(r_datum) > 1 or l_datum[0].value == r_datum[0].value): # NOTE(sileht): should we do something if the expression # match multiple fields, for now ignore them continue elif l_datum[0].value < r_datum[0].value: return 1 if reverse else -1 else: return -1 if reverse else 1 return 0 def find(self, datum): """Return sorted value of This if list or dict.""" if isinstance(datum.value, dict) and self.expressions: return datum if isinstance(datum.value, dict) or isinstance(datum.value, list): key = (functools.cmp_to_key(self._compare) if self.expressions else None) return [DatumInContext.wrap( [value for value in sorted(datum.value, key=key)])] return datum def __eq__(self, other): return isinstance(other, Len) def __repr__(self): return '%s(%r)' % (self.__class__.__name__, self.expressions) def __str__(self): return '[?%s]' % self.expressions class Len(JSONPath): """The JSONPath referring to the len of the current object. Concrete syntax is '`len`'. """ def find(self, datum): datum = DatumInContext.wrap(datum) try: value = len(datum.value) except TypeError: return [] else: return [DatumInContext(value, context=None, path=Len())] def __eq__(self, other): return isinstance(other, Len) def __str__(self): return '`len`' def __repr__(self): return 'Len()' class Keys(JSONPath): """The JSONPath referring to the keys of the current object. Concrete syntax is '`keys`'. """ def find(self, datum): datum = DatumInContext.wrap(datum) try: value = list(datum.value.keys()) except Exception as e: return [] else: return [DatumInContext(value[i], context=None, path=Keys()) for i in range (0, len(datum.value))] def __eq__(self, other): return isinstance(other, Keys) def __str__(self): return '`keys`' def __repr__(self): return 'Keys()' ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1695653930.0 jsonpath-ng-1.6.1/jsonpath_ng/ext/parser.py0000664000175100017510000001234714504320052020025 0ustar00mmiormmior# # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from .. import lexer from .. import parser from .. import Fields, This, Child from . import arithmetic as _arithmetic from . import filter as _filter from . import iterable as _iterable from . import string as _string class ExtendedJsonPathLexer(lexer.JsonPathLexer): """Custom LALR-lexer for JsonPath""" literals = lexer.JsonPathLexer.literals + ['?', '@', '+', '*', '/', '-'] tokens = (['BOOL'] + parser.JsonPathLexer.tokens + ['FILTER_OP', 'SORT_DIRECTION', 'FLOAT']) t_FILTER_OP = r'=~|==?|<=|>=|!=|<|>' def t_BOOL(self, t): r'true|false' t.value = True if t.value == 'true' else False return t def t_SORT_DIRECTION(self, t): r',?\s*(/|\\)' t.value = t.value[-1] return t def t_ID(self, t): r'@?[a-zA-Z_][a-zA-Z0-9_@\-]*' # NOTE(sileht): This fixes the ID expression to be # able to use @ for `This` like any json query t.type = self.reserved_words.get(t.value, 'ID') return t def t_FLOAT(self, t): r'-?\d+\.\d+' t.value = float(t.value) return t class ExtentedJsonPathParser(parser.JsonPathParser): """Custom LALR-parser for JsonPath""" tokens = ExtendedJsonPathLexer.tokens def __init__(self, debug=False, lexer_class=None): lexer_class = lexer_class or ExtendedJsonPathLexer super(ExtentedJsonPathParser, self).__init__(debug, lexer_class) def p_jsonpath_operator_jsonpath(self, p): """jsonpath : NUMBER operator NUMBER | FLOAT operator FLOAT | ID operator ID | NUMBER operator jsonpath | FLOAT operator jsonpath | jsonpath operator NUMBER | jsonpath operator FLOAT | jsonpath operator jsonpath """ # NOTE(sileht): If we have choice between a field or a string we # always choice string, because field can be full qualified # like $.foo == foo and where string can't. for i in [1, 3]: if (isinstance(p[i], Fields) and len(p[i].fields) == 1): # noqa p[i] = p[i].fields[0] p[0] = _arithmetic.Operation(p[1], p[2], p[3]) def p_operator(self, p): """operator : '+' | '-' | '*' | '/' """ p[0] = p[1] def p_jsonpath_named_operator(self, p): "jsonpath : NAMED_OPERATOR" if p[1] == 'len': p[0] = _iterable.Len() elif p[1] == 'keys': p[0] = _iterable.Keys() elif p[1] == 'sorted': p[0] = _iterable.SortedThis() elif p[1].startswith("split("): p[0] = _string.Split(p[1]) elif p[1].startswith("sub("): p[0] = _string.Sub(p[1]) elif p[1].startswith("str("): p[0] = _string.Str(p[1]) else: super(ExtentedJsonPathParser, self).p_jsonpath_named_operator(p) def p_expression(self, p): """expression : jsonpath | jsonpath FILTER_OP ID | jsonpath FILTER_OP FLOAT | jsonpath FILTER_OP NUMBER | jsonpath FILTER_OP BOOL """ if len(p) == 2: left, op, right = p[1], None, None else: __, left, op, right = p p[0] = _filter.Expression(left, op, right) def p_expressions_expression(self, p): "expressions : expression" p[0] = [p[1]] def p_expressions_and(self, p): "expressions : expressions '&' expressions" # TODO(sileht): implements '|' p[0] = p[1] + p[3] def p_expressions_parens(self, p): "expressions : '(' expressions ')'" p[0] = p[2] def p_filter(self, p): "filter : '?' expressions " p[0] = _filter.Filter(p[2]) def p_jsonpath_filter(self, p): "jsonpath : jsonpath '[' filter ']'" p[0] = Child(p[1], p[3]) def p_sort(self, p): "sort : SORT_DIRECTION jsonpath" p[0] = (p[2], p[1] != "/") def p_sorts_sort(self, p): "sorts : sort" p[0] = [p[1]] def p_sorts_comma(self, p): "sorts : sorts sorts" p[0] = p[1] + p[2] def p_jsonpath_sort(self, p): "jsonpath : jsonpath '[' sorts ']'" sort = _iterable.SortedThis(p[3]) p[0] = Child(p[1], sort) def p_jsonpath_this(self, p): "jsonpath : '@'" p[0] = This() precedence = [ ('left', '+', '-'), ('left', '*', '/'), ] + parser.JsonPathParser.precedence + [ ('nonassoc', 'ID'), ] def parse(path, debug=False): return ExtentedJsonPathParser(debug=debug).parse(path) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1695646157.0 jsonpath-ng-1.6.1/jsonpath_ng/ext/string.py0000664000175100017510000000627514504300715020046 0ustar00mmiormmior# # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import re from .. import DatumInContext, This SUB = re.compile(r"sub\(/(.*)/,\s+(.*)\)") SPLIT = re.compile(r"split\((.),\s+(\d+),\s+(\d+|-1)\)") STR = re.compile(r"str\(\)") class DefintionInvalid(Exception): pass class Sub(This): """Regex substituor Concrete syntax is '`sub(/regex/, repl)`' """ def __init__(self, method=None): m = SUB.match(method) if m is None: raise DefintionInvalid("%s is not valid" % method) self.expr = m.group(1).strip() self.repl = m.group(2).strip() self.regex = re.compile(self.expr) self.method = method def find(self, datum): datum = DatumInContext.wrap(datum) value = self.regex.sub(self.repl, datum.value) if value == datum.value: return [] else: return [DatumInContext.wrap(value)] def __eq__(self, other): return (isinstance(other, Sub) and self.method == other.method) def __repr__(self): return '%s(%r)' % (self.__class__.__name__, self.method) def __str__(self): return '`sub(/%s/, %s)`' % (self.expr, self.repl) class Split(This): """String splitter Concrete syntax is '`split(char, segment, max_split)`' """ def __init__(self, method=None): m = SPLIT.match(method) if m is None: raise DefintionInvalid("%s is not valid" % method) self.char = m.group(1) self.segment = int(m.group(2)) self.max_split = int(m.group(3)) self.method = method def find(self, datum): datum = DatumInContext.wrap(datum) try: value = datum.value.split(self.char, self.max_split)[self.segment] except Exception: return [] return [DatumInContext.wrap(value)] def __eq__(self, other): return (isinstance(other, Split) and self.method == other.method) def __repr__(self): return '%s(%r)' % (self.__class__.__name__, self.method) def __str__(self): return '`%s`' % self.method class Str(This): """String converter Concrete syntax is '`str()`' """ def __init__(self, method=None): m = STR.match(method) if m is None: raise DefintionInvalid("%s is not valid" % method) self.method = method def find(self, datum): datum = DatumInContext.wrap(datum) value = str(datum.value) return [DatumInContext.wrap(value)] def __eq__(self, other): return (isinstance(other, Str) and self.method == other.method) def __repr__(self): return '%s(%r)' % (self.__class__.__name__, self.method) def __str__(self): return '`str()`' ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1699968179.0 jsonpath-ng-1.6.1/jsonpath_ng/jsonpath.py0000664000175100017510000006344214524672263017601 0ustar00mmiormmiorimport logging from itertools import * # noqa from jsonpath_ng.lexer import JsonPathLexer # Get logger name logger = logging.getLogger(__name__) # Turn on/off the automatic creation of id attributes # ... could be a kwarg pervasively but uses are rare and simple today auto_id_field = None NOT_SET = object() LIST_KEY = object() class JSONPath: """ The base class for JSONPath abstract syntax; those methods stubbed here are the interface to supported JSONPath semantics. """ def find(self, data): """ All `JSONPath` types support `find()`, which returns an iterable of `DatumInContext`s. They keep track of the path followed to the current location, so if the calling code has some opinion about that, it can be passed in here as a starting point. """ raise NotImplementedError() def find_or_create(self, data): return self.find(data) def update(self, data, val): """ Returns `data` with the specified path replaced by `val`. Only updates if the specified path exists. """ raise NotImplementedError() def update_or_create(self, data, val): return self.update(data, val) def filter(self, fn, data): """ Returns `data` with the specified path filtering nodes according the filter evaluation result returned by the filter function. Arguments: fn (function): unary function that accepts one argument and returns bool. data (dict|list|tuple): JSON object to filter. """ raise NotImplementedError() def child(self, child): """ Equivalent to Child(self, next) but with some canonicalization """ if isinstance(self, This) or isinstance(self, Root): return child elif isinstance(child, This): return self elif isinstance(child, Root): return child else: return Child(self, child) def make_datum(self, value): if isinstance(value, DatumInContext): return value else: return DatumInContext(value, path=Root(), context=None) class DatumInContext: """ Represents a datum along a path from a context. Essentially a zipper but with a structure represented by JsonPath, and where the context is more of a parent pointer than a proper representation of the context. For quick-and-dirty work, this proxies any non-special attributes to the underlying datum, but the actual datum can (and usually should) be retrieved via the `value` attribute. To place `datum` within another, use `datum.in_context(context=..., path=...)` which extends the path. If the datum already has a context, it places the entire context within that passed in, so an object can be built from the inside out. """ @classmethod def wrap(cls, data): if isinstance(data, cls): return data else: return cls(data) def __init__(self, value, path=None, context=None): self.value = value self.path = path or This() self.context = None if context is None else DatumInContext.wrap(context) def in_context(self, context, path): context = DatumInContext.wrap(context) if self.context: return DatumInContext(value=self.value, path=self.path, context=context.in_context(path=path, context=context)) else: return DatumInContext(value=self.value, path=path, context=context) @property def full_path(self): return self.path if self.context is None else self.context.full_path.child(self.path) @property def id_pseudopath(self): """ Looks like a path, but with ids stuck in when available """ try: pseudopath = Fields(str(self.value[auto_id_field])) except (TypeError, AttributeError, KeyError): # This may not be all the interesting exceptions pseudopath = self.path if self.context: return self.context.id_pseudopath.child(pseudopath) else: return pseudopath def __repr__(self): return '%s(value=%r, path=%r, context=%r)' % (self.__class__.__name__, self.value, self.path, self.context) def __eq__(self, other): return isinstance(other, DatumInContext) and other.value == self.value and other.path == self.path and self.context == other.context class AutoIdForDatum(DatumInContext): """ This behaves like a DatumInContext, but the value is always the path leading up to it, not including the "id", and with any "id" fields along the way replacing the prior segment of the path For example, it will make "foo.bar.id" return a datum that behaves like DatumInContext(value="foo.bar", path="foo.bar.id"). This is disabled by default; it can be turned on by settings the `auto_id_field` global to a value other than `None`. """ def __init__(self, datum, id_field=None): """ Invariant is that datum.path is the path from context to datum. The auto id will either be the id in the datum (if present) or the id of the context followed by the path to the datum. The path to this datum is always the path to the context, the path to the datum, and then the auto id field. """ self.datum = datum self.id_field = id_field or auto_id_field @property def value(self): return str(self.datum.id_pseudopath) @property def path(self): return self.id_field @property def context(self): return self.datum def __repr__(self): return '%s(%r)' % (self.__class__.__name__, self.datum) def in_context(self, context, path): return AutoIdForDatum(self.datum.in_context(context=context, path=path)) def __eq__(self, other): return isinstance(other, AutoIdForDatum) and other.datum == self.datum and self.id_field == other.id_field class Root(JSONPath): """ The JSONPath referring to the "root" object. Concrete syntax is '$'. The root is the topmost datum without any context attached. """ def find(self, data): if not isinstance(data, DatumInContext): return [DatumInContext(data, path=Root(), context=None)] else: if data.context is None: return [DatumInContext(data.value, context=None, path=Root())] else: return Root().find(data.context) def update(self, data, val): return val def filter(self, fn, data): return data if fn(data) else None def __str__(self): return '$' def __repr__(self): return 'Root()' def __eq__(self, other): return isinstance(other, Root) def __hash__(self): return hash('$') class This(JSONPath): """ The JSONPath referring to the current datum. Concrete syntax is '@'. """ def find(self, datum): return [DatumInContext.wrap(datum)] def update(self, data, val): return val def filter(self, fn, data): return data if fn(data) else None def __str__(self): return '`this`' def __repr__(self): return 'This()' def __eq__(self, other): return isinstance(other, This) def __hash__(self): return hash('this') class Child(JSONPath): """ JSONPath that first matches the left, then the right. Concrete syntax is '.' """ def __init__(self, left, right): self.left = left self.right = right def find(self, datum): """ Extra special case: auto ids do not have children, so cut it off right now rather than auto id the auto id """ return [submatch for subdata in self.left.find(datum) if not isinstance(subdata, AutoIdForDatum) for submatch in self.right.find(subdata)] def update(self, data, val): for datum in self.left.find(data): self.right.update(datum.value, val) return data def find_or_create(self, datum): datum = DatumInContext.wrap(datum) submatches = [] for subdata in self.left.find_or_create(datum): if isinstance(subdata, AutoIdForDatum): # Extra special case: auto ids do not have children, # so cut it off right now rather than auto id the auto id continue for submatch in self.right.find_or_create(subdata): submatches.append(submatch) return submatches def update_or_create(self, data, val): for datum in self.left.find_or_create(data): self.right.update_or_create(datum.value, val) return _clean_list_keys(data) def filter(self, fn, data): for datum in self.left.find(data): self.right.filter(fn, datum.value) return data def __eq__(self, other): return isinstance(other, Child) and self.left == other.left and self.right == other.right def __str__(self): return '%s.%s' % (self.left, self.right) def __repr__(self): return '%s(%r, %r)' % (self.__class__.__name__, self.left, self.right) def __hash__(self): return hash((self.left, self.right)) class Parent(JSONPath): """ JSONPath that matches the parent node of the current match. Will crash if no such parent exists. Available via named operator `parent`. """ def find(self, datum): datum = DatumInContext.wrap(datum) return [datum.context] def __eq__(self, other): return isinstance(other, Parent) def __str__(self): return '`parent`' def __repr__(self): return 'Parent()' def __hash__(self): return hash('parent') class Where(JSONPath): """ JSONPath that first matches the left, and then filters for only those nodes that have a match on the right. WARNING: Subject to change. May want to have "contains" or some other better word for it. """ def __init__(self, left, right): self.left = left self.right = right def find(self, data): return [subdata for subdata in self.left.find(data) if self.right.find(subdata)] def update(self, data, val): for datum in self.find(data): datum.path.update(data, val) return data def filter(self, fn, data): for datum in self.find(data): datum.path.filter(fn, datum.value) return data def __str__(self): return '%s where %s' % (self.left, self.right) def __eq__(self, other): return isinstance(other, Where) and other.left == self.left and other.right == self.right def __hash__(self): return hash((self.left, self.right)) class Descendants(JSONPath): """ JSONPath that matches first the left expression then any descendant of it which matches the right expression. """ def __init__(self, left, right): self.left = left self.right = right def find(self, datum): # .. ==> . ( | *.. | [*]..) # # With with a wonky caveat that since Slice() has funky coercions # we cannot just delegate to that equivalence or we'll hit an # infinite loop. So right here we implement the coercion-free version. # Get all left matches into a list left_matches = self.left.find(datum) if not isinstance(left_matches, list): left_matches = [left_matches] def match_recursively(datum): right_matches = self.right.find(datum) # Manually do the * or [*] to avoid coercion and recurse just the right-hand pattern if isinstance(datum.value, list): recursive_matches = [submatch for i in range(0, len(datum.value)) for submatch in match_recursively(DatumInContext(datum.value[i], context=datum, path=Index(i)))] elif isinstance(datum.value, dict): recursive_matches = [submatch for field in datum.value.keys() for submatch in match_recursively(DatumInContext(datum.value[field], context=datum, path=Fields(field)))] else: recursive_matches = [] return right_matches + list(recursive_matches) # TODO: repeatable iterator instead of list? return [submatch for left_match in left_matches for submatch in match_recursively(left_match)] def is_singular(self): return False def update(self, data, val): # Get all left matches into a list left_matches = self.left.find(data) if not isinstance(left_matches, list): left_matches = [left_matches] def update_recursively(data): # Update only mutable values corresponding to JSON types if not (isinstance(data, list) or isinstance(data, dict)): return self.right.update(data, val) # Manually do the * or [*] to avoid coercion and recurse just the right-hand pattern if isinstance(data, list): for i in range(0, len(data)): update_recursively(data[i]) elif isinstance(data, dict): for field in data.keys(): update_recursively(data[field]) for submatch in left_matches: update_recursively(submatch.value) return data def filter(self, fn, data): # Get all left matches into a list left_matches = self.left.find(data) if not isinstance(left_matches, list): left_matches = [left_matches] def filter_recursively(data): # Update only mutable values corresponding to JSON types if not (isinstance(data, list) or isinstance(data, dict)): return self.right.filter(fn, data) # Manually do the * or [*] to avoid coercion and recurse just the right-hand pattern if isinstance(data, list): for i in range(0, len(data)): filter_recursively(data[i]) elif isinstance(data, dict): for field in data.keys(): filter_recursively(data[field]) for submatch in left_matches: filter_recursively(submatch.value) return data def __str__(self): return '%s..%s' % (self.left, self.right) def __eq__(self, other): return isinstance(other, Descendants) and self.left == other.left and self.right == other.right def __repr__(self): return '%s(%r, %r)' % (self.__class__.__name__, self.left, self.right) def __hash__(self): return hash((self.left, self.right)) class Union(JSONPath): """ JSONPath that returns the union of the results of each match. This is pretty shoddily implemented for now. The nicest semantics in case of mismatched bits (list vs atomic) is to put them all in a list, but I haven't done that yet. WARNING: Any appearance of this being the _concatenation_ is coincidence. It may even be a bug! (or laziness) """ def __init__(self, left, right): self.left = left self.right = right def is_singular(self): return False def find(self, data): return self.left.find(data) + self.right.find(data) def __eq__(self, other): return isinstance(other, Union) and self.left == other.left and self.right == other.right def __hash__(self): return hash((self.left, self.right)) class Intersect(JSONPath): """ JSONPath for bits that match *both* patterns. This can be accomplished a couple of ways. The most efficient is to actually build the intersected AST as in building a state machine for matching the intersection of regular languages. The next idea is to build a filtered data and match against that. """ def __init__(self, left, right): self.left = left self.right = right def is_singular(self): return False def find(self, data): raise NotImplementedError() def __eq__(self, other): return isinstance(other, Intersect) and self.left == other.left and self.right == other.right def __hash__(self): return hash((self.left, self.right)) class Fields(JSONPath): """ JSONPath referring to some field of the current object. Concrete syntax ix comma-separated field names. WARNING: If '*' is any of the field names, then they will all be returned. """ def __init__(self, *fields): self.fields = fields @staticmethod def get_field_datum(datum, field, create): if field == auto_id_field: return AutoIdForDatum(datum) try: field_value = datum.value.get(field, NOT_SET) if field_value is NOT_SET: if create: datum.value[field] = field_value = {} else: return None return DatumInContext(field_value, path=Fields(field), context=datum) except (TypeError, AttributeError): return None def reified_fields(self, datum): if '*' not in self.fields: return self.fields else: try: fields = tuple(datum.value.keys()) return fields if auto_id_field is None else fields + (auto_id_field,) except AttributeError: return () def find(self, datum): return self._find_base(datum, create=False) def find_or_create(self, datum): return self._find_base(datum, create=True) def _find_base(self, datum, create): datum = DatumInContext.wrap(datum) field_data = [self.get_field_datum(datum, field, create) for field in self.reified_fields(datum)] return [fd for fd in field_data if fd is not None] def update(self, data, val): return self._update_base(data, val, create=False) def update_or_create(self, data, val): return self._update_base(data, val, create=True) def _update_base(self, data, val, create): if data is not None: for field in self.reified_fields(DatumInContext.wrap(data)): if field not in data and create: data[field] = {} if field in data: if hasattr(val, '__call__'): data[field] = val(data[field], data, field) else: data[field] = val return data def filter(self, fn, data): if data is not None: for field in self.reified_fields(DatumInContext.wrap(data)): if field in data: if fn(data[field]): data.pop(field) return data def __str__(self): # If any JsonPathLexer.literals are included in field name need quotes # This avoids unnecessary quotes to keep strings short. # Test each field whether it contains a literal and only then add quotes # The test loops over all literals, could possibly optimize to short circuit if one found fields_as_str = ("'" + str(f) + "'" if any([l in f for l in JsonPathLexer.literals]) else str(f) for f in self.fields) return ','.join(fields_as_str) def __repr__(self): return '%s(%s)' % (self.__class__.__name__, ','.join(map(repr, self.fields))) def __eq__(self, other): return isinstance(other, Fields) and tuple(self.fields) == tuple(other.fields) def __hash__(self): return hash(tuple(self.fields)) class Index(JSONPath): """ JSONPath that matches indices of the current datum, or none if not large enough. Concrete syntax is brackets. WARNING: If the datum is None or not long enough, it will not crash but will not match anything. NOTE: For the concrete syntax of `[*]`, the abstract syntax is a Slice() with no parameters (equiv to `[:]` """ def __init__(self, index): self.index = index def find(self, datum): return self._find_base(datum, create=False) def find_or_create(self, datum): return self._find_base(datum, create=True) def _find_base(self, datum, create): datum = DatumInContext.wrap(datum) if create: if datum.value == {}: datum.value = _create_list_key(datum.value) self._pad_value(datum.value) if datum.value and len(datum.value) > self.index: return [DatumInContext(datum.value[self.index], path=self, context=datum)] else: return [] def update(self, data, val): return self._update_base(data, val, create=False) def update_or_create(self, data, val): return self._update_base(data, val, create=True) def _update_base(self, data, val, create): if create: if data == {}: data = _create_list_key(data) self._pad_value(data) if hasattr(val, '__call__'): data[self.index] = val.__call__(data[self.index], data, self.index) elif len(data) > self.index: data[self.index] = val return data def filter(self, fn, data): if fn(data[self.index]): data.pop(self.index) # relies on mutation :( return data def __eq__(self, other): return isinstance(other, Index) and self.index == other.index def __str__(self): return '[%i]' % self.index def __repr__(self): return '%s(index=%r)' % (self.__class__.__name__, self.index) def _pad_value(self, value): if len(value) <= self.index: pad = self.index - len(value) + 1 value += [{} for __ in range(pad)] def __hash__(self): return hash(self.index) class Slice(JSONPath): """ JSONPath matching a slice of an array. Because of a mismatch between JSON and XML when schema-unaware, this always returns an iterable; if the incoming data was not a list, then it returns a one element list _containing_ that data. Consider these two docs, and their schema-unaware translation to JSON: hello ==> {"a": {"b": "hello"}} hellogoodbye ==> {"a": {"b": ["hello", "goodbye"]}} If there were a schema, it would be known that "b" should always be an array (unless the schema were wonky, but that is too much to fix here) so when querying with JSON if the one writing the JSON knows that it should be an array, they can write a slice operator and it will coerce a non-array value to an array. This may be a bit unfortunate because it would be nice to always have an iterator, but dictionaries and other objects may also be iterable, so this is the compromise. """ def __init__(self, start=None, end=None, step=None): self.start = start self.end = end self.step = step def find(self, datum): datum = DatumInContext.wrap(datum) # Used for catching null value instead of empty list in path if not datum.value: return [] # Here's the hack. If it is a dictionary or some kind of constant, # put it in a single-element list if (isinstance(datum.value, dict) or isinstance(datum.value, int) or isinstance(datum.value, str)): return self.find(DatumInContext([datum.value], path=datum.path, context=datum.context)) # Some iterators do not support slicing but we can still # at least work for '*' if self.start is None and self.end is None and self.step is None: return [DatumInContext(datum.value[i], path=Index(i), context=datum) for i in range(0, len(datum.value))] else: return [DatumInContext(datum.value[i], path=Index(i), context=datum) for i in range(0, len(datum.value))[self.start:self.end:self.step]] def update(self, data, val): for datum in self.find(data): datum.path.update(data, val) return data def filter(self, fn, data): while True: length = len(data) for datum in self.find(data): data = datum.path.filter(fn, data) if len(data) < length: break if length == len(data): break return data def __str__(self): if self.start is None and self.end is None and self.step is None: return '[*]' else: return '[%s%s%s]' % (self.start or '', ':%d'%self.end if self.end else '', ':%d'%self.step if self.step else '') def __repr__(self): return '%s(start=%r,end=%r,step=%r)' % (self.__class__.__name__, self.start, self.end, self.step) def __eq__(self, other): return isinstance(other, Slice) and other.start == self.start and self.end == other.end and other.step == self.step def __hash__(self): return hash((self.start, self.end, self.step)) def _create_list_key(dict_): """ Adds a list to a dictionary by reference and returns the list. See `_clean_list_keys()` """ dict_[LIST_KEY] = new_list = [{}] return new_list def _clean_list_keys(struct_): """ Replace {LIST_KEY: ['foo', 'bar']} with ['foo', 'bar']. >>> _clean_list_keys({LIST_KEY: ['foo', 'bar']}) ['foo', 'bar'] """ if(isinstance(struct_, list)): for ind, value in enumerate(struct_): struct_[ind] = _clean_list_keys(value) elif(isinstance(struct_, dict)): if(LIST_KEY in struct_): return _clean_list_keys(struct_[LIST_KEY]) else: for key, value in struct_.items(): struct_[key] = _clean_list_keys(value) return struct_ ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1699968179.0 jsonpath-ng-1.6.1/jsonpath_ng/lexer.py0000664000175100017510000001215714524672263017067 0ustar00mmiormmiorimport sys import logging import ply.lex from jsonpath_ng.exceptions import JsonPathLexerError logger = logging.getLogger(__name__) class JsonPathLexer: ''' A Lexical analyzer for JsonPath. ''' def __init__(self, debug=False): self.debug = debug if self.__doc__ is None: raise JsonPathLexerError('Docstrings have been removed! By design of PLY, jsonpath-rw requires docstrings. You must not use PYTHONOPTIMIZE=2 or python -OO.') def tokenize(self, string): ''' Maps a string to an iterator over tokens. In other words: [char] -> [token] ''' new_lexer = ply.lex.lex(module=self, debug=self.debug, errorlog=logger) new_lexer.latest_newline = 0 new_lexer.string_value = None new_lexer.input(string) while True: t = new_lexer.token() if t is None: break t.col = t.lexpos - new_lexer.latest_newline yield t if new_lexer.string_value is not None: raise JsonPathLexerError('Unexpected EOF in string literal or identifier') # ============== PLY Lexer specification ================== # # This probably should be private but: # - the parser requires access to `tokens` (perhaps they should be defined in a third, shared dependency) # - things like `literals` might be a legitimate part of the public interface. # # Anyhow, it is pythonic to give some rope to hang oneself with :-) literals = ['*', '.', '[', ']', '(', ')', '$', ',', ':', '|', '&', '~'] reserved_words = { 'where': 'WHERE' } tokens = ['DOUBLEDOT', 'NUMBER', 'ID', 'NAMED_OPERATOR'] + list(reserved_words.values()) states = [ ('singlequote', 'exclusive'), ('doublequote', 'exclusive'), ('backquote', 'exclusive') ] # Normal lexing, rather easy t_DOUBLEDOT = r'\.\.' t_ignore = ' \t' def t_ID(self, t): r'[a-zA-Z_@][a-zA-Z0-9_@\-]*' t.type = self.reserved_words.get(t.value, 'ID') return t def t_NUMBER(self, t): r'-?\d+' t.value = int(t.value) return t # Single-quoted strings t_singlequote_ignore = '' def t_singlequote(self, t): r"'" t.lexer.string_start = t.lexer.lexpos t.lexer.string_value = '' t.lexer.push_state('singlequote') def t_singlequote_content(self, t): r"[^'\\]+" t.lexer.string_value += t.value def t_singlequote_escape(self, t): r'\\.' t.lexer.string_value += t.value[1] def t_singlequote_end(self, t): r"'" t.value = t.lexer.string_value t.type = 'ID' t.lexer.string_value = None t.lexer.pop_state() return t def t_singlequote_error(self, t): raise JsonPathLexerError('Error on line %s, col %s while lexing singlequoted field: Unexpected character: %s ' % (t.lexer.lineno, t.lexpos - t.lexer.latest_newline, t.value[0])) # Double-quoted strings t_doublequote_ignore = '' def t_doublequote(self, t): r'"' t.lexer.string_start = t.lexer.lexpos t.lexer.string_value = '' t.lexer.push_state('doublequote') def t_doublequote_content(self, t): r'[^"\\]+' t.lexer.string_value += t.value def t_doublequote_escape(self, t): r'\\.' t.lexer.string_value += t.value[1] def t_doublequote_end(self, t): r'"' t.value = t.lexer.string_value t.type = 'ID' t.lexer.string_value = None t.lexer.pop_state() return t def t_doublequote_error(self, t): raise JsonPathLexerError('Error on line %s, col %s while lexing doublequoted field: Unexpected character: %s ' % (t.lexer.lineno, t.lexpos - t.lexer.latest_newline, t.value[0])) # Back-quoted "magic" operators t_backquote_ignore = '' def t_backquote(self, t): r'`' t.lexer.string_start = t.lexer.lexpos t.lexer.string_value = '' t.lexer.push_state('backquote') def t_backquote_escape(self, t): r'\\.' t.lexer.string_value += t.value[1] def t_backquote_content(self, t): r"[^`\\]+" t.lexer.string_value += t.value def t_backquote_end(self, t): r'`' t.value = t.lexer.string_value t.type = 'NAMED_OPERATOR' t.lexer.string_value = None t.lexer.pop_state() return t def t_backquote_error(self, t): raise JsonPathLexerError('Error on line %s, col %s while lexing backquoted operator: Unexpected character: %s ' % (t.lexer.lineno, t.lexpos - t.lexer.latest_newline, t.value[0])) # Counting lines, handling errors def t_newline(self, t): r'\n' t.lexer.lineno += 1 t.lexer.latest_newline = t.lexpos def t_error(self, t): raise JsonPathLexerError('Error on line %s, col %s: Unexpected character: %s ' % (t.lexer.lineno, t.lexpos - t.lexer.latest_newline, t.value[0])) if __name__ == '__main__': logging.basicConfig() lexer = JsonPathLexer(debug=True) for token in lexer.tokenize(sys.stdin.read()): print('%-20s%s' % (token.value, token.type)) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1699968179.0 jsonpath-ng-1.6.1/jsonpath_ng/parser.py0000664000175100017510000001337314524672263017245 0ustar00mmiormmiorimport logging import sys import os.path import ply.yacc from jsonpath_ng.exceptions import JsonPathParserError from jsonpath_ng.jsonpath import * from jsonpath_ng.lexer import JsonPathLexer logger = logging.getLogger(__name__) def parse(string): return JsonPathParser().parse(string) class JsonPathParser: ''' An LALR-parser for JsonPath ''' tokens = JsonPathLexer.tokens def __init__(self, debug=False, lexer_class=None): if self.__doc__ is None: raise JsonPathParserError( 'Docstrings have been removed! By design of PLY, ' 'jsonpath-rw requires docstrings. You must not use ' 'PYTHONOPTIMIZE=2 or python -OO.' ) self.debug = debug self.lexer_class = lexer_class or JsonPathLexer # Crufty but works around statefulness in PLY def parse(self, string, lexer = None): lexer = lexer or self.lexer_class() return self.parse_token_stream(lexer.tokenize(string)) def parse_token_stream(self, token_iterator, start_symbol='jsonpath'): # Since PLY has some crufty aspects and dumps files, we try to keep them local # However, we need to derive the name of the output Python file :-/ output_directory = os.path.dirname(__file__) try: module_name = os.path.splitext(os.path.split(__file__)[1])[0] except: module_name = __name__ parsing_table_module = '_'.join([module_name, start_symbol, 'parsetab']) # And we regenerate the parse table every time; # it doesn't actually take that long! new_parser = ply.yacc.yacc(module=self, debug=self.debug, tabmodule = parsing_table_module, outputdir = output_directory, write_tables=0, start = start_symbol, errorlog = logger) return new_parser.parse(lexer = IteratorToTokenStream(token_iterator)) # ===================== PLY Parser specification ===================== precedence = [ ('left', ','), ('left', 'DOUBLEDOT'), ('left', '.'), ('left', '|'), ('left', '&'), ('left', 'WHERE'), ] def p_error(self, t): if t is None: raise JsonPathParserError('Parse error near the end of string!') raise JsonPathParserError('Parse error at %s:%s near token %s (%s)' % (t.lineno, t.col, t.value, t.type)) def p_jsonpath_binop(self, p): """jsonpath : jsonpath '.' jsonpath | jsonpath DOUBLEDOT jsonpath | jsonpath WHERE jsonpath | jsonpath '|' jsonpath | jsonpath '&' jsonpath""" op = p[2] if op == '.': p[0] = Child(p[1], p[3]) elif op == '..': p[0] = Descendants(p[1], p[3]) elif op == 'where': p[0] = Where(p[1], p[3]) elif op == '|': p[0] = Union(p[1], p[3]) elif op == '&': p[0] = Intersect(p[1], p[3]) def p_jsonpath_fields(self, p): "jsonpath : fields_or_any" p[0] = Fields(*p[1]) def p_jsonpath_named_operator(self, p): "jsonpath : NAMED_OPERATOR" if p[1] == 'this': p[0] = This() elif p[1] == 'parent': p[0] = Parent() else: raise JsonPathParserError('Unknown named operator `%s` at %s:%s' % (p[1], p.lineno(1), p.lexpos(1))) def p_jsonpath_root(self, p): "jsonpath : '$'" p[0] = Root() def p_jsonpath_idx(self, p): "jsonpath : '[' idx ']'" p[0] = p[2] def p_jsonpath_slice(self, p): "jsonpath : '[' slice ']'" p[0] = p[2] def p_jsonpath_fieldbrackets(self, p): "jsonpath : '[' fields ']'" p[0] = Fields(*p[2]) def p_jsonpath_child_fieldbrackets(self, p): "jsonpath : jsonpath '[' fields ']'" p[0] = Child(p[1], Fields(*p[3])) def p_jsonpath_child_idxbrackets(self, p): "jsonpath : jsonpath '[' idx ']'" p[0] = Child(p[1], p[3]) def p_jsonpath_child_slicebrackets(self, p): "jsonpath : jsonpath '[' slice ']'" p[0] = Child(p[1], p[3]) def p_jsonpath_parens(self, p): "jsonpath : '(' jsonpath ')'" p[0] = p[2] # Because fields in brackets cannot be '*' - that is reserved for array indices def p_fields_or_any(self, p): """fields_or_any : fields | '*' """ if p[1] == '*': p[0] = ['*'] else: p[0] = p[1] def p_fields_id(self, p): "fields : ID" p[0] = [p[1]] def p_fields_comma(self, p): "fields : fields ',' fields" p[0] = p[1] + p[3] def p_idx(self, p): "idx : NUMBER" p[0] = Index(p[1]) def p_slice_any(self, p): "slice : '*'" p[0] = Slice() def p_slice(self, p): # Currently does not support `step` """slice : maybe_int ':' maybe_int | maybe_int ':' maybe_int ':' maybe_int """ p[0] = Slice(*p[1::2]) def p_maybe_int(self, p): """maybe_int : NUMBER | empty""" p[0] = p[1] def p_empty(self, p): 'empty :' p[0] = None class IteratorToTokenStream: def __init__(self, iterator): self.iterator = iterator def token(self): try: return next(self.iterator) except StopIteration: return None if __name__ == '__main__': logging.basicConfig() parser = JsonPathParser(debug=True) print(parser.parse(sys.stdin.read())) ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1705001033.7198036 jsonpath-ng-1.6.1/jsonpath_ng.egg-info/0000775000175100017510000000000014550040112017037 5ustar00mmiormmior././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1705001033.0 jsonpath-ng-1.6.1/jsonpath_ng.egg-info/PKG-INFO0000664000175100017510000004320514550040111020137 0ustar00mmiormmiorMetadata-Version: 2.1 Name: jsonpath-ng Version: 1.6.1 Summary: A final implementation of JSONPath for Python that aims to be standard compliant, including arithmetic and binary comparison operators and providing clear AST for metaprogramming. Home-page: https://github.com/h2non/jsonpath-ng Author: Tomas Aparicio Author-email: tomas@aparicio.me License: Apache 2.0 Classifier: Development Status :: 5 - Production/Stable Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: Apache Software License Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: 3.7 Classifier: Programming Language :: Python :: 3.8 Classifier: Programming Language :: Python :: 3.9 Classifier: Programming Language :: Python :: 3.10 Classifier: Programming Language :: Python :: 3.11 Classifier: Programming Language :: Python :: 3.12 License-File: LICENSE Python JSONPath Next-Generation |Build Status| |PyPI| ===================================================== A final implementation of JSONPath for Python that aims to be standard compliant, including arithmetic and binary comparison operators, as defined in the original `JSONPath proposal`_. This packages merges both `jsonpath-rw`_ and `jsonpath-rw-ext`_ and provides several AST API enhancements, such as the ability to update or remove nodes in the tree. About ----- This library provides a robust and significantly extended implementation of JSONPath for Python. It is tested with CPython 3.7 and higher. This library differs from other JSONPath implementations in that it is a full *language* implementation, meaning the JSONPath expressions are first class objects, easy to analyze, transform, parse, print, and extend. Quick Start ----------- To install, use pip: .. code:: bash $ pip install --upgrade jsonpath-ng Usage ----- Basic examples: .. code:: python $ python >>> from jsonpath_ng import jsonpath, parse # A robust parser, not just a regex. (Makes powerful extensions possible; see below) >>> jsonpath_expr = parse('foo[*].baz') # Extracting values is easy >>> [match.value for match in jsonpath_expr.find({'foo': [{'baz': 1}, {'baz': 2}]})] [1, 2] # Matches remember where they came from >>> [str(match.full_path) for match in jsonpath_expr.find({'foo': [{'baz': 1}, {'baz': 2}]})] ['foo.[0].baz', 'foo.[1].baz'] # Modifying values matching the path >>> jsonpath_expr.update( {'foo': [{'baz': 1}, {'baz': 2}]}, 3) {'foo': [{'baz': 3}, {'baz': 3}]} # Modifying one of the values matching the path >>> matches = jsonpath_expr.find({'foo': [{'baz': 1}, {'baz': 2}]}) >>> matches[0].full_path.update( {'foo': [{'baz': 1}, {'baz': 2}]}, 3) {'foo': [{'baz': 3}, {'baz': 2}]} # Removing all values matching a path >>> jsonpath_expr.filter(lambda d: True, {'foo': [{'baz': 1}, {'baz': 2}]}) {'foo': [{}, {}]} # Removing values containing particular data matching path >>> jsonpath_expr.filter(lambda d: d == 2, {'foo': [{'baz': 1}, {'baz': 2}]}) {'foo': [{'baz': 1}, {}]} # And this can be useful for automatically providing ids for bits of data that do not have them (currently a global switch) >>> jsonpath.auto_id_field = 'id' >>> [match.value for match in parse('foo[*].id').find({'foo': [{'id': 'bizzle'}, {'baz': 3}]})] ['foo.bizzle', 'foo.[1]'] # A handy extension: named operators like `parent` >>> [match.value for match in parse('a.*.b.`parent`.c').find({'a': {'x': {'b': 1, 'c': 'number one'}, 'y': {'b': 2, 'c': 'number two'}}})] ['number two', 'number one'] # You can also build expressions directly quite easily >>> from jsonpath_ng.jsonpath import Fields >>> from jsonpath_ng.jsonpath import Slice >>> jsonpath_expr_direct = Fields('foo').child(Slice('*')).child(Fields('baz')) # This is equivalent Using the extended parser: .. code:: python $ python >>> from jsonpath_ng.ext import parse # A robust parser, not just a regex. (Makes powerful extensions possible; see below) >>> jsonpath_expr = parse('foo[*].baz') JSONPath Syntax --------------- The JSONPath syntax supported by this library includes some additional features and omits some problematic features (those that make it unportable). In particular, some new operators such as ``|`` and ``where`` are available, and parentheses are used for grouping not for callbacks into Python, since with these changes the language is not trivially associative. Also, fields may be quoted whether or not they are contained in brackets. Atomic expressions: +-----------------------+---------------------------------------------------------------------------------------------+ | Syntax | Meaning | +=======================+=============================================================================================+ | ``$`` | The root object | +-----------------------+---------------------------------------------------------------------------------------------+ | ```this``` | The "current" object. | +-----------------------+---------------------------------------------------------------------------------------------+ | ```foo``` | More generally, this syntax allows "named operators" to extend JSONPath is arbitrary ways | +-----------------------+---------------------------------------------------------------------------------------------+ | *field* | Specified field(s), described below | +-----------------------+---------------------------------------------------------------------------------------------+ | ``[`` *field* ``]`` | Same as *field* | +-----------------------+---------------------------------------------------------------------------------------------+ | ``[`` *idx* ``]`` | Array access, described below (this is always unambiguous with field access) | +-----------------------+---------------------------------------------------------------------------------------------+ Jsonpath operators: +-------------------------------------+------------------------------------------------------------------------------------+ | Syntax | Meaning | +=====================================+====================================================================================+ | *jsonpath1* ``.`` *jsonpath2* | All nodes matched by *jsonpath2* starting at any node matching *jsonpath1* | +-------------------------------------+------------------------------------------------------------------------------------+ | *jsonpath* ``[`` *whatever* ``]`` | Same as *jsonpath*\ ``.``\ *whatever* | +-------------------------------------+------------------------------------------------------------------------------------+ | *jsonpath1* ``..`` *jsonpath2* | All nodes matched by *jsonpath2* that descend from any node matching *jsonpath1* | +-------------------------------------+------------------------------------------------------------------------------------+ | *jsonpath1* ``where`` *jsonpath2* | Any nodes matching *jsonpath1* with a child matching *jsonpath2* | +-------------------------------------+------------------------------------------------------------------------------------+ | *jsonpath1* ``|`` *jsonpath2* | Any nodes matching the union of *jsonpath1* and *jsonpath2* | +-------------------------------------+------------------------------------------------------------------------------------+ Field specifiers ( *field* ): +-------------------------+-------------------------------------------------------------------------------------+ | Syntax | Meaning | +=========================+=====================================================================================+ | ``fieldname`` | the field ``fieldname`` (from the "current" object) | +-------------------------+-------------------------------------------------------------------------------------+ | ``"fieldname"`` | same as above, for allowing special characters in the fieldname | +-------------------------+-------------------------------------------------------------------------------------+ | ``'fieldname'`` | ditto | +-------------------------+-------------------------------------------------------------------------------------+ | ``*`` | any field | +-------------------------+-------------------------------------------------------------------------------------+ | *field* ``,`` *field* | either of the named fields (you can always build equivalent jsonpath using ``|``) | +-------------------------+-------------------------------------------------------------------------------------+ Array specifiers ( *idx* ): +-----------------------------------------+---------------------------------------------------------------------------------------+ | Syntax | Meaning | +=========================================+=======================================================================================+ | ``[``\ *n*\ ``]`` | array index (may be comma-separated list) | +-----------------------------------------+---------------------------------------------------------------------------------------+ | ``[``\ *start*\ ``?:``\ *end*\ ``?]`` | array slicing (note that *step* is unimplemented only due to lack of need thus far) | +-----------------------------------------+---------------------------------------------------------------------------------------+ | ``[*]`` | any array index | +-----------------------------------------+---------------------------------------------------------------------------------------+ Programmatic JSONPath --------------------- If you are programming in Python and would like a more robust way to create JSONPath expressions that does not depend on a parser, it is very easy to do so directly, and here are some examples: - ``Root()`` - ``Slice(start=0, end=None, step=None)`` - ``Fields('foo', 'bar')`` - ``Index(42)`` - ``Child(Fields('foo'), Index(42))`` - ``Where(Slice(), Fields('subfield'))`` - ``Descendants(jsonpath, jsonpath)`` Extras ------ - *Path data*: The result of ``JsonPath.find`` provide detailed context and path data so it is easy to traverse to parent objects, print full paths to pieces of data, and generate automatic ids. - *Automatic Ids*: If you set ``jsonpath_ng.auto_id_field`` to a value other than None, then for any piece of data missing that field, it will be replaced by the JSONPath to it, giving automatic unique ids to any piece of data. These ids will take into account any ids already present as well. - *Named operators*: Instead of using ``@`` to reference the current object, this library uses ```this```. In general, any string contained in backquotes can be made to be a new operator, currently by extending the library. Extensions ---------- To use the extensions below you must import from `jsonpath_ng.ext`. +--------------+-----------------------------------------------+ | name | Example | +==============+===============================================+ | len | - ``$.objects.`len``` | +--------------+-----------------------------------------------+ | sub | - ``$.field.`sub(/foo\\\\+(.*)/, \\\\1)``` | | | - ``$.field.`sub(/regex/, replacement)``` | +--------------+-----------------------------------------------+ | split | - ``$.field.`split(+, 2, -1)``` | | | - ``$.field.`split(sep, segement, maxsplit)```| +--------------+-----------------------------------------------+ | sorted | - ``$.objects.`sorted``` | | | - ``$.objects[\\some_field]`` | | | - ``$.objects[\\some_field,/other_field]`` | +--------------+-----------------------------------------------+ | filter | - ``$.objects[?(@some_field > 5)]`` | | | - ``$.objects[?some_field = "foobar"]`` | | | - ``$.objects[?some_field =~ "foobar"]`` | | | - ``$.objects[?some_field > 5 & other < 2]`` | | | | | | Supported operators: | | | - Equality: ==, =, != | | | - Comparison: >, >=, <, <= | | | - Regex match: =~ | | | | | | Combine multiple criteria with '&'. | | | | | | Properties can only be compared to static | | | values. | +--------------+-----------------------------------------------+ | arithmetic | - ``$.foo + "_" + $.bar`` | | (-+*/) | - ``$.foo * 12`` | | | - ``$.objects[*].cow + $.objects[*].cat`` | +--------------+-----------------------------------------------+ About arithmetic and string --------------------------- Operations are done with python operators and allows types that python allows, and return [] if the operation can be done due to incompatible types. When operators are used, a jsonpath must be be fully defined otherwise jsonpath-rw-ext can't known if the expression is a string or a jsonpath field, in this case it will choice string as type. Example with data:: { 'cow': 'foo', 'fish': 'bar' } | ``cow + fish`` returns ``cowfish`` | ``$.cow + $.fish`` returns ``foobar`` | ``$.cow + "_" + $.fish`` returns ``foo_bar`` | ``$.cow + "_" + fish`` returns ``foo_fish`` About arithmetic and list ------------------------- Arithmetic can be used against two lists if they have the same size. Example with data:: {'objects': [ {'cow': 2, 'cat': 3}, {'cow': 4, 'cat': 6} ]} | ``$.objects[\*].cow + $.objects[\*].cat`` returns ``[6, 9]`` More to explore --------------- There are way too many JSONPath implementations out there to discuss. Some are robust, some are toy projects that still work fine, some are exercises. There will undoubtedly be many more. This one is made for use in released, maintained code, and in particular for programmatic access to the abstract syntax and extension. But JSONPath at its simplest just isn't that complicated, so you can probably use any of them successfully. Why not this one? The original proposal, as far as I know: - `JSONPath - XPath for JSON `__ by Stefan Goessner. Other examples -------------- Loading json data from file .. code:: python import json d = json.loads('{"foo": [{"baz": 1}, {"baz": 2}]}') # or with open('myfile.json') as f: d = json.load(f) Special note about PLY and docstrings ------------------------------------- The main parsing toolkit underlying this library, `PLY `__, does not work with docstrings removed. For example, ``PYTHONOPTIMIZE=2`` and ``python -OO`` will both cause a failure. Contributors ------------ This package is authored and maintained by: - `Kenn Knowles `__ (`@kennknowles `__) - `Tomas Aparicio ` with the help of patches submitted by `these contributors `__. Copyright and License --------------------- Copyright 2013 - Kenneth Knowles Copyright 2017 - Tomas Aparicio Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at :: http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. .. _`JSONPath proposal`: http://goessner.net/articles/JsonPath/ .. _`jsonpath-rw`: https://github.com/kennknowles/python-jsonpath-rw .. _`jsonpath-rw-ext`: https://pypi.python.org/pypi/jsonpath-rw-ext/ .. |PyPi downloads| image:: https://pypip.in/d/jsonpath-ng/badge.png :target: https://pypi.python.org/pypi/jsonpath-ng .. |Build Status| image:: https://github.com/h2non/jsonpath-ng/actions/workflows/ci.yml/badge.svg :target: https://github.com/h2non/jsonpath-ng/actions/workflows/ci.yml .. |PyPI| image:: https://img.shields.io/pypi/v/jsonpath-ng.svg?maxAge=2592000?style=flat-square :target: https://pypi.python.org/pypi/jsonpath-ng ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1705001033.0 jsonpath-ng-1.6.1/jsonpath_ng.egg-info/SOURCES.txt0000664000175100017510000000157014550040111020725 0ustar00mmiormmiorLICENSE MANIFEST.in README.rst pyproject.toml setup.py jsonpath_ng/__init__.py jsonpath_ng/exceptions.py jsonpath_ng/jsonpath.py jsonpath_ng/lexer.py jsonpath_ng/parser.py jsonpath_ng.egg-info/PKG-INFO jsonpath_ng.egg-info/SOURCES.txt jsonpath_ng.egg-info/dependency_links.txt jsonpath_ng.egg-info/entry_points.txt jsonpath_ng.egg-info/requires.txt jsonpath_ng.egg-info/top_level.txt jsonpath_ng/bin/__init__.py jsonpath_ng/bin/jsonpath.py jsonpath_ng/ext/__init__.py jsonpath_ng/ext/arithmetic.py jsonpath_ng/ext/filter.py jsonpath_ng/ext/iterable.py jsonpath_ng/ext/parser.py jsonpath_ng/ext/string.py tests/__init__.py tests/conftest.py tests/helpers.py tests/test_create.py tests/test_examples.py tests/test_exceptions.py tests/test_jsonpath.py tests/test_jsonpath_rw_ext.py tests/test_lexer.py tests/test_parser.py tests/bin/test1.json tests/bin/test2.json tests/bin/test_jsonpath.py././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1705001033.0 jsonpath-ng-1.6.1/jsonpath_ng.egg-info/dependency_links.txt0000664000175100017510000000000114550040111023104 0ustar00mmiormmior ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1705001033.0 jsonpath-ng-1.6.1/jsonpath_ng.egg-info/entry_points.txt0000664000175100017510000000010514550040111022330 0ustar00mmiormmior[console_scripts] jsonpath_ng = jsonpath_ng.bin.jsonpath:entry_point ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1705001033.0 jsonpath-ng-1.6.1/jsonpath_ng.egg-info/requires.txt0000664000175100017510000000000414550040111021430 0ustar00mmiormmiorply ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1705001033.0 jsonpath-ng-1.6.1/jsonpath_ng.egg-info/top_level.txt0000664000175100017510000000001414550040111021563 0ustar00mmiormmiorjsonpath_ng ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1695646159.0 jsonpath-ng-1.6.1/pyproject.toml0000664000175100017510000000031414504300717015756 0ustar00mmiormmior[tool.pytest.ini_options] filterwarnings = [ # Escalate warnings to errors. "error", # The ply package doesn't close its debug log file. Ignore this warning. "ignore::ResourceWarning", ] ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1705001033.7198036 jsonpath-ng-1.6.1/setup.cfg0000664000175100017510000000004614550040112014654 0ustar00mmiormmior[egg_info] tag_build = tag_date = 0 ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1705000712.0 jsonpath-ng-1.6.1/setup.py0000664000175100017510000000247014550037410014557 0ustar00mmiormmiorimport io import setuptools setuptools.setup( name='jsonpath-ng', version='1.6.1', description=( 'A final implementation of JSONPath for Python that aims to be ' 'standard compliant, including arithmetic and binary comparison ' 'operators and providing clear AST for metaprogramming.' ), author='Tomas Aparicio', author_email='tomas@aparicio.me', url='https://github.com/h2non/jsonpath-ng', license='Apache 2.0', long_description=io.open('README.rst', encoding='utf-8').read(), packages=['jsonpath_ng', 'jsonpath_ng.bin', 'jsonpath_ng.ext'], entry_points={ 'console_scripts': [ 'jsonpath_ng=jsonpath_ng.bin.jsonpath:entry_point' ], }, test_suite='tests', install_requires=[ 'ply' ], classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: 3.9', 'Programming Language :: Python :: 3.10', 'Programming Language :: Python :: 3.11', 'Programming Language :: Python :: 3.12', ], ) ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1705001033.7198036 jsonpath-ng-1.6.1/tests/0000775000175100017510000000000014550040112014175 5ustar00mmiormmior././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1689268185.0 jsonpath-ng-1.6.1/tests/__init__.py0000664000175100017510000000000014454027731016313 0ustar00mmiormmior././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1705001033.7198036 jsonpath-ng-1.6.1/tests/bin/0000775000175100017510000000000014550040112014745 5ustar00mmiormmior././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1689268185.0 jsonpath-ng-1.6.1/tests/bin/test1.json0000664000175100017510000000013314454027731016714 0ustar00mmiormmior{ "foo": { "baz": 1, "bizzle": { "baz": 2 } } }././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1689268185.0 jsonpath-ng-1.6.1/tests/bin/test2.json0000664000175100017510000000020414454027731016714 0ustar00mmiormmior{ "foo": { "foo": { "baz": 3, "merp": { "baz": 4 } } } }././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1699968179.0 jsonpath-ng-1.6.1/tests/bin/test_jsonpath.py0000664000175100017510000000144114524672263020227 0ustar00mmiormmior""" Tests for the jsonpath.py command line interface. """ import io import json import os import sys from jsonpath_ng.bin.jsonpath import main def test_stdin_mode(monkeypatch, capsys): stdin_text = json.dumps( { "foo": { "baz": 1, "bizzle": {"baz": 2}, }, } ) monkeypatch.setattr(sys, "stdin", io.StringIO(stdin_text)) main("jsonpath.py", "foo..baz") stdout, _ = capsys.readouterr() assert stdout == "1\n2\n" def test_filename_mode(capsys): test1 = os.path.join(os.path.dirname(__file__), "test1.json") test2 = os.path.join(os.path.dirname(__file__), "test2.json") main("jsonpath.py", "foo..baz", test1, test2) stdout, _ = capsys.readouterr() assert stdout == "1\n2\n3\n4\n" ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1699968179.0 jsonpath-ng-1.6.1/tests/conftest.py0000664000175100017510000000062314524672263016420 0ustar00mmiormmiorimport pytest @pytest.fixture(autouse=True) def disable_auto_id_field(monkeypatch): monkeypatch.setattr("jsonpath_ng.jsonpath.auto_id_field", None) @pytest.fixture() def auto_id_field(monkeypatch, disable_auto_id_field): """Enable `jsonpath_ng.jsonpath.auto_id_field`.""" field_name = "id" monkeypatch.setattr("jsonpath_ng.jsonpath.auto_id_field", field_name) return field_name ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1699968179.0 jsonpath-ng-1.6.1/tests/helpers.py0000664000175100017510000000273314524672263016241 0ustar00mmiormmiordef assert_value_equality(results, expected_values): """Assert equality between two objects. *results* must be a list of results as returned by `.find()` methods. If *expected_values* is a list, then value equality and ordering will be checked. If *expected_values* is a set, value equality and container length will be checked. Otherwise, the value of the results will be compared to the expected values. """ left_values = [result.value for result in results] if isinstance(expected_values, list): assert left_values == expected_values elif isinstance(expected_values, set): assert len(left_values) == len(expected_values) assert set(left_values) == expected_values else: assert results[0].value == expected_values def assert_full_path_equality(results, expected_full_paths): """Assert equality between two objects. *results* must be a list or set of results as returned by `.find()` methods. If *expected_full_paths* is a list, then path equality and ordering will be checked. If *expected_full_paths* is a set, then path equality and length will be checked. """ full_paths = [str(result.full_path) for result in results] if isinstance(expected_full_paths, list): assert full_paths == expected_full_paths, full_paths else: # isinstance(expected_full_paths, set): assert len(full_paths) == len(expected_full_paths) assert set(full_paths) == expected_full_paths ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1699968179.0 jsonpath-ng-1.6.1/tests/test_create.py0000664000175100017510000000420014524672263017070 0ustar00mmiormmiorimport copy from contextlib import nullcontext as does_not_raise import pytest from jsonpath_ng.ext import parse @pytest.mark.parametrize( "string, initial_data, expected_result", ( ("$.foo", {}, {"foo": 42}), ("$.foo.bar", {}, {"foo": {"bar": 42}}), ("$.foo[0]", {}, {"foo": [42]}), ("$.foo[1]", {}, {"foo": [{}, 42]}), ("$.foo[0].bar", {}, {"foo": [{"bar": 42}]}), ("$.foo[1].bar", {}, {"foo": [{}, {"bar": 42}]}), ("$.foo[0][0]", {}, {"foo": [[42]]}), ("$.foo[1][1]", {}, {"foo": [{}, [{}, 42]]}), ("foo[0]", {}, {"foo": [42]}), ("foo[1]", {}, {"foo": [{}, 42]}), ("foo", {}, {"foo": 42}), # # Initial data can be a list if we expect a list back. ("[0]", [], [42]), ("[1]", [], [{}, 42]), # # Convert initial data to a list, if necessary. ("[0]", {}, [42]), ("[1]", {}, [{}, 42]), # ( 'foo[?bar="baz"].qux', { "foo": [ {"bar": "baz"}, {"bar": "bizzle"}, ] }, {"foo": [{"bar": "baz", "qux": 42}, {"bar": "bizzle"}]}, ), ("[1].foo", [{"foo": 1}, {"bar": 2}], [{"foo": 1}, {"foo": 42, "bar": 2}]), ), ) def test_update_or_create(string, initial_data, expected_result): jsonpath = parse(string) result = jsonpath.update_or_create(initial_data, 42) assert result == expected_result @pytest.mark.parametrize( "string, initial_data, expectation", ( # Slice not supported ("foo[0:1]", {}, does_not_raise()), # # Filter does not create items to meet criteria ('foo[?bar="baz"].qux', {}, does_not_raise()), # # Does not convert initial data to a dictionary ("foo", [], pytest.raises(TypeError)), ), ) def test_unsupported_classes(string, initial_data, expectation): copied_initial_data = copy.copy(initial_data) jsonpath = parse(string) with expectation: result = jsonpath.update_or_create(initial_data, 42) assert result != copied_initial_data ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1699968179.0 jsonpath-ng-1.6.1/tests/test_examples.py0000664000175100017510000000462414524672263017455 0ustar00mmiormmiorimport pytest from jsonpath_ng.ext import parse from jsonpath_ng.ext.filter import Expression, Filter from jsonpath_ng.jsonpath import Child, Descendants, Fields, Index, Root, Slice, This @pytest.mark.parametrize( "string, parsed", [ # The authors of all books in the store ( "$.store.book[*].author", Child( Child(Child(Child(Root(), Fields("store")), Fields("book")), Slice()), Fields("author"), ), ), # # All authors ("$..author", Descendants(Root(), Fields("author"))), # # All things in the store ("$.store.*", Child(Child(Root(), Fields("store")), Fields("*"))), # # The price of everything in the store ( "$.store..price", Descendants(Child(Root(), Fields("store")), Fields("price")), ), # # The third book ("$..book[2]", Child(Descendants(Root(), Fields("book")), Index(2))), # # The last book in order # "$..book[(@.length-1)]" # Not implemented ("$..book[-1:]", Child(Descendants(Root(), Fields("book")), Slice(start=-1))), # # The first two books # "$..book[0,1]" # Not implemented ("$..book[:2]", Child(Descendants(Root(), Fields("book")), Slice(end=2))), # # Filter all books with an ISBN ( "$..book[?(@.isbn)]", Child( Descendants(Root(), Fields("book")), Filter([Expression(Child(This(), Fields("isbn")), None, None)]), ), ), # # Filter all books cheaper than 10 ( "$..book[?(@.price<10)]", Child( Descendants(Root(), Fields("book")), Filter([Expression(Child(This(), Fields("price")), "<", 10)]), ), ), # # All members of JSON structure ("$..*", Descendants(Root(), Fields("*"))), ], ) def test_goessner_examples(string, parsed): """ Test Stefan Goessner's `examples`_ .. _examples: https://goessner.net/articles/JsonPath/index.html#e3 """ assert parse(string, debug=True) == parsed def test_attribute_and_dict_syntax(): """Verify that attribute and dict syntax result in identical parse trees.""" assert parse("$.store.book[0].title") == parse("$['store']['book'][0]['title']") ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1699968179.0 jsonpath-ng-1.6.1/tests/test_exceptions.py0000664000175100017510000000133114524672263020010 0ustar00mmiormmiorimport pytest from jsonpath_ng import parse as base_parse from jsonpath_ng.exceptions import JsonPathParserError from jsonpath_ng.ext import parse as ext_parse @pytest.mark.parametrize( "path", ( "foo[*.bar.baz", "foo.bar.`grandparent`.baz", "foo[*", # `len` extension not available in the base parser "foo.bar.`len`", ), ) def test_rw_exception_subclass(path): with pytest.raises(JsonPathParserError): base_parse(path) @pytest.mark.parametrize( "path", ( "foo[*.bar.baz", "foo.bar.`grandparent`.baz", "foo[*", ), ) def test_ext_exception_subclass(path): with pytest.raises(JsonPathParserError): ext_parse(path) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1699968179.0 jsonpath-ng-1.6.1/tests/test_jsonpath.py0000664000175100017510000002276214524672263017470 0ustar00mmiormmiorimport copy import pytest from jsonpath_ng.ext.parser import parse as ext_parse from jsonpath_ng.jsonpath import DatumInContext, Fields, Root, This from jsonpath_ng.lexer import JsonPathLexerError from jsonpath_ng.parser import parse as base_parse from .helpers import assert_full_path_equality, assert_value_equality @pytest.mark.parametrize( "path_arg, context_arg, expected_path, expected_full_path", ( (None, None, This(), This()), (Root(), None, Root(), Root()), (Fields("foo"), "unimportant", Fields("foo"), Fields("foo")), ( Fields("foo"), DatumInContext("unimportant", path=Fields("baz"), context="unimportant"), Fields("foo"), Fields("baz").child(Fields("foo")), ), ), ) def test_datumincontext_init(path_arg, context_arg, expected_path, expected_full_path): datum = DatumInContext(3, path=path_arg, context=context_arg) assert datum.path == expected_path assert datum.full_path == expected_full_path def test_datumincontext_in_context(): d1 = DatumInContext(3, path=Fields("foo"), context=DatumInContext("bar")) d2 = DatumInContext(3).in_context(path=Fields("foo"), context=DatumInContext("bar")) assert d1 == d2 def test_datumincontext_in_context_nested(): sequential_calls = ( DatumInContext(3) .in_context(path=Fields("foo"), context="whatever") .in_context(path=Fields("baz"), context="whatever") ) nested_calls = DatumInContext(3).in_context( path=Fields("foo"), context=DatumInContext("whatever").in_context( path=Fields("baz"), context="whatever" ), ) assert sequential_calls == nested_calls parsers = pytest.mark.parametrize( "parse", ( pytest.param(base_parse, id="parse=jsonpath_ng.parser.parse"), pytest.param(ext_parse, id="parse=jsonpath_ng.ext.parser.parse"), ), ) update_test_cases = ( # # Fields # ------ # ("foo", {"foo": 1}, 5, {"foo": 5}), ("$.*", {"foo": 1, "bar": 2}, 3, {"foo": 3, "bar": 3}), # # Indexes # ------- # ("[0]", ["foo", "bar", "baz"], "test", ["test", "bar", "baz"]), # # Slices # ------ # ("[0:2]", ["foo", "bar", "baz"], "test", ["test", "test", "baz"]), # # Root # ---- # ("$", "foo", "bar", "bar"), # # This # ---- # ("`this`", "foo", "bar", "bar"), # # Children # -------- # ("$.foo", {"foo": "bar"}, "baz", {"foo": "baz"}), ("foo.bar", {"foo": {"bar": 1}}, "baz", {"foo": {"bar": "baz"}}), # # Descendants # ----------- # ("$..somefield", {"somefield": 1}, 42, {"somefield": 42}), ( "$..nestedfield", {"outer": {"nestedfield": 1}}, 42, {"outer": {"nestedfield": 42}}, ), ( "$..bar", {"outs": {"bar": 1, "ins": {"bar": 9}}, "outs2": {"bar": 2}}, 42, {"outs": {"bar": 42, "ins": {"bar": 42}}, "outs2": {"bar": 42}}, ), # # Where # ----- # ( "*.bar where baz", {"foo": {"bar": {"baz": 1}}, "bar": {"baz": 2}}, 5, {"foo": {"bar": 5}, "bar": {"baz": 2}}, ), ( "(* where flag) .. bar", {"foo": {"bar": 1, "flag": 1}, "baz": {"bar": 2}}, 3, {"foo": {"bar": 3, "flag": 1}, "baz": {"bar": 2}}, ), # # Lambdas # ------- # ( "foo[*].baz", {'foo': [{'baz': 1}, {'baz': 2}]}, lambda x, y, z: x + 1, {'foo': [{'baz': 2}, {'baz': 3}]} ), ) @pytest.mark.parametrize( "expression, data, update_value, expected_value", update_test_cases, ) @parsers def test_update(parse, expression, data, update_value, expected_value): data_copy = copy.deepcopy(data) result = parse(expression).update(data_copy, update_value) assert result == expected_value find_test_cases = ( # # * (star) # -------- # ("*", {"foo": 1, "baz": 2}, {1, 2}, {"foo", "baz"}), # # Fields # ------ # ("foo", {"foo": "baz"}, ["baz"], ["foo"]), ("foo,baz", {"foo": 1, "baz": 2}, [1, 2], ["foo", "baz"]), ("@foo", {"@foo": 1}, [1], ["@foo"]), # # Roots # ----- # ("$", {"foo": "baz"}, [{"foo": "baz"}], ["$"]), ("foo.$", {"foo": "baz"}, [{"foo": "baz"}], ["$"]), ("foo.$.foo", {"foo": "baz"}, ["baz"], ["foo"]), # # This # ---- # ("`this`", {"foo": "baz"}, [{"foo": "baz"}], ["`this`"]), ("foo.`this`", {"foo": "baz"}, ["baz"], ["foo"]), ("foo.`this`.baz", {"foo": {"baz": 3}}, [3], ["foo.baz"]), # # Indexes # ------- # ("[0]", [42], [42], ["[0]"]), ("[5]", [42], [], []), ("[2]", [34, 65, 29, 59], [29], ["[2]"]), ("[0]", None, [], []), # # Slices # ------ # ("[*]", [1, 2, 3], [1, 2, 3], ["[0]", "[1]", "[2]"]), ("[*]", range(1, 4), [1, 2, 3], ["[0]", "[1]", "[2]"]), ("[1:]", [1, 2, 3, 4], [2, 3, 4], ["[1]", "[2]", "[3]"]), ("[1:3]", [1, 2, 3, 4], [2, 3], ["[1]", "[2]"]), ("[:2]", [1, 2, 3, 4], [1, 2], ["[0]", "[1]"]), ("[:3:2]", [1, 2, 3, 4], [1, 3], ["[0]", "[2]"]), ("[1::2]", [1, 2, 3, 4], [2, 4], ["[1]", "[3]"]), ("[1:6:3]", range(1, 10), [2, 5], ["[1]", "[4]"]), ("[::-2]", [1, 2, 3, 4, 5], [5, 3, 1], ["[4]", "[2]", "[0]"]), # # Slices (funky hacks) # -------------------- # ("[*]", 1, [1], ["[0]"]), ("[0:]", 1, [1], ["[0]"]), ("[*]", {"foo": 1}, [{"foo": 1}], ["[0]"]), ("[*].foo", {"foo": 1}, [1], ["[0].foo"]), # # Children # -------- # ("foo.baz", {"foo": {"baz": 3}}, [3], ["foo.baz"]), ("foo.baz", {"foo": {"baz": [3]}}, [[3]], ["foo.baz"]), ("foo.baz.qux", {"foo": {"baz": {"qux": 5}}}, [5], ["foo.baz.qux"]), # # Descendants # ----------- # ( "foo..baz", {"foo": {"baz": 1, "bing": {"baz": 2}}}, [1, 2], ["foo.baz", "foo.bing.baz"], ), ( "foo..baz", {"foo": [{"baz": 1}, {"baz": 2}]}, [1, 2], ["foo.[0].baz", "foo.[1].baz"], ), # # Parents # ------- # ("foo.baz.`parent`", {"foo": {"baz": 3}}, [{"baz": 3}], ["foo"]), ( "foo.`parent`.foo.baz.`parent`.baz.qux", {"foo": {"baz": {"qux": 5}}}, [5], ["foo.baz.qux"], ), # # Hyphens # ------- # ("foo.bar-baz", {"foo": {"bar-baz": 3}}, [3], ["foo.bar-baz"]), ( "foo.[bar-baz,blah-blah]", {"foo": {"bar-baz": 3, "blah-blah": 5}}, [3, 5], ["foo.bar-baz", "foo.blah-blah"], ), # # Literals # -------- # ("A.'a.c'", {"A": {"a.c": "d"}}, ["d"], ["A.'a.c'"]), ) @pytest.mark.parametrize( "path, data, expected_values, expected_full_paths", find_test_cases ) @parsers def test_find(parse, path, data, expected_values, expected_full_paths): results = parse(path).find(data) # Verify result values and full paths match expectations. assert_value_equality(results, expected_values) assert_full_path_equality(results, expected_full_paths) find_test_cases_with_auto_id = ( # # * (star) # -------- # ("*", {"foo": 1, "baz": 2}, {1, 2, "`this`"}), # # Fields # ------ # ("foo.id", {"foo": "baz"}, ["foo"]), ("foo.id", {"foo": {"id": "baz"}}, ["baz"]), ("foo,baz.id", {"foo": 1, "baz": 2}, ["foo", "baz"]), ("*.id", {"foo": {"id": 1}, "baz": 2}, {"1", "baz"}), # # Roots # ----- # ("$.id", {"foo": "baz"}, ["$"]), ("foo.$.id", {"foo": "baz", "id": "bizzle"}, ["bizzle"]), ("foo.$.baz.id", {"foo": 4, "baz": 3}, ["baz"]), # # This # ---- # ("id", {"foo": "baz"}, ["`this`"]), ("foo.`this`.id", {"foo": "baz"}, ["foo"]), ("foo.`this`.baz.id", {"foo": {"baz": 3}}, ["foo.baz"]), # # Indexes # ------- # ("[0].id", [42], ["[0]"]), ("[2].id", [34, 65, 29, 59], ["[2]"]), # # Slices # ------ # ("[*].id", [1, 2, 3], ["[0]", "[1]", "[2]"]), ("[1:].id", [1, 2, 3, 4], ["[1]", "[2]", "[3]"]), # # Children # -------- # ("foo.baz.id", {"foo": {"baz": 3}}, ["foo.baz"]), ("foo.baz.id", {"foo": {"baz": [3]}}, ["foo.baz"]), ("foo.baz.id", {"foo": {"id": "bizzle", "baz": 3}}, ["bizzle.baz"]), ("foo.baz.id", {"foo": {"baz": {"id": "hi"}}}, ["foo.hi"]), ("foo.baz.bizzle.id", {"foo": {"baz": {"bizzle": 5}}}, ["foo.baz.bizzle"]), # # Descendants # ----------- # ( "foo..baz.id", {"foo": {"baz": 1, "bing": {"baz": 2}}}, ["foo.baz", "foo.bing.baz"], ), ) @pytest.mark.parametrize("path, data, expected_values", find_test_cases_with_auto_id) @parsers def test_find_values_auto_id(auto_id_field, parse, path, data, expected_values): result = parse(path).find(data) assert_value_equality(result, expected_values) @parsers def test_find_full_paths_auto_id(auto_id_field, parse): results = parse("*").find({"foo": 1, "baz": 2}) assert_full_path_equality(results, {"foo", "baz", "id"}) @pytest.mark.parametrize( "string, target", ( ("m.[1].id", ["1.m.a2id"]), ("m.[1].$.b.id", ["1.bid"]), ("m.[0].id", ["1.m.[0]"]), ), ) @parsers def test_nested_index_auto_id(auto_id_field, parse, string, target): data = { "id": 1, "b": {"id": "bid", "name": "bob"}, "m": [{"a": "a1"}, {"a": "a2", "id": "a2id"}], } result = parse(string).find(data) assert_value_equality(result, target) def test_invalid_hyphenation_in_key(): with pytest.raises(JsonPathLexerError): base_parse("foo.-baz") ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1699968179.0 jsonpath-ng-1.6.1/tests/test_jsonpath_rw_ext.py0000664000175100017510000003216214524672263021053 0ustar00mmiormmior""" test_jsonpath_ng_ext ---------------------------------- Tests for `jsonpath_ng_ext` module. """ import pytest from jsonpath_ng.exceptions import JsonPathParserError from jsonpath_ng.ext import parser from .helpers import assert_value_equality test_cases = ( pytest.param( "objects.`sorted`", {"objects": ["alpha", "gamma", "beta"]}, [["alpha", "beta", "gamma"]], id="sorted_list", ), pytest.param( "objects.`sorted`[1]", {"objects": ["alpha", "gamma", "beta"]}, "beta", id="sorted_list_indexed", ), pytest.param( "objects.`sorted`", {"objects": {"cow": "moo", "horse": "neigh", "cat": "meow"}}, [["cat", "cow", "horse"]], id="sorted_dict", ), pytest.param( "objects.`sorted`[0]", {"objects": {"cow": "moo", "horse": "neigh", "cat": "meow"}}, "cat", id="sorted_dict_indexed", ), pytest.param( "objects.`len`", {"objects": ["alpha", "gamma", "beta"]}, 3, id="len_list" ), pytest.param( "objects.`len`", {"objects": {"cow": "moo", "cat": "neigh"}}, 2, id="len_dict" ), pytest.param("objects[0].`len`", {"objects": ["alpha", "gamma"]}, 5, id="len_str"), pytest.param( 'objects[?@="alpha"]', {"objects": ["alpha", "gamma", "beta"]}, ["alpha"], id="filter_list", ), pytest.param( 'objects[?@ =~ "a.+"]', {"objects": ["alpha", "gamma", "beta"]}, ["alpha", "gamma"], id="filter_list_2", ), pytest.param( 'objects[?@ =~ "a.+"]', {"objects": [1, 2, 3]}, [], id="filter_list_3" ), pytest.param( "objects.`keys`", {"objects": ["alpha", "gamma", "beta"]}, [], id="keys_list" ), pytest.param( "objects.`keys`", {"objects": {"cow": "moo", "cat": "neigh"}}, ["cow", "cat"], id="keys_dict", ), pytest.param( "objects[?cow]", {"objects": [{"cow": "moo"}, {"cat": "neigh"}]}, [{"cow": "moo"}], id="filter_exists_syntax1", ), pytest.param( "objects[?@.cow]", {"objects": [{"cow": "moo"}, {"cat": "neigh"}]}, [{"cow": "moo"}], id="filter_exists_syntax2", ), pytest.param( "objects[?(@.cow)]", {"objects": [{"cow": "moo"}, {"cat": "neigh"}]}, [{"cow": "moo"}], id="filter_exists_syntax3", ), pytest.param( 'objects[?(@."cow!?cat")]', {"objects": [{"cow!?cat": "moo"}, {"cat": "neigh"}]}, [{"cow!?cat": "moo"}], id="filter_exists_syntax4", ), pytest.param( 'objects[?cow="moo"]', {"objects": [{"cow": "moo"}, {"cow": "neigh"}, {"cat": "neigh"}]}, [{"cow": "moo"}], id="filter_eq1", ), pytest.param( 'objects[?(@.["cow"]="moo")]', {"objects": [{"cow": "moo"}, {"cow": "neigh"}, {"cat": "neigh"}]}, [{"cow": "moo"}], id="filter_eq2", ), pytest.param( 'objects[?cow=="moo"]', {"objects": [{"cow": "moo"}, {"cow": "neigh"}, {"cat": "neigh"}]}, [{"cow": "moo"}], id="filter_eq3", ), pytest.param( "objects[?cow>5]", {"objects": [{"cow": 8}, {"cow": 7}, {"cow": 5}, {"cow": "neigh"}]}, [{"cow": 8}, {"cow": 7}], id="filter_gt", ), pytest.param( "objects[?cow>5&cat=2]", { "objects": [ {"cow": 8, "cat": 2}, {"cow": 7, "cat": 2}, {"cow": 2, "cat": 2}, {"cow": 5, "cat": 3}, {"cow": 8, "cat": 3}, ] }, [{"cow": 8, "cat": 2}, {"cow": 7, "cat": 2}], id="filter_and", ), pytest.param( "objects[?confidence>=0.5].prediction", { "objects": [ {"confidence": 0.42, "prediction": "Good"}, {"confidence": 0.58, "prediction": "Bad"}, ] }, ["Bad"], id="filter_float_gt", ), pytest.param( "objects[/cow]", { "objects": [ {"cat": 1, "cow": 2}, {"cat": 2, "cow": 1}, {"cat": 3, "cow": 3}, ] }, [[{"cat": 2, "cow": 1}, {"cat": 1, "cow": 2}, {"cat": 3, "cow": 3}]], id="sort1", ), pytest.param( "objects[/cow][0].cat", { "objects": [ {"cat": 1, "cow": 2}, {"cat": 2, "cow": 1}, {"cat": 3, "cow": 3}, ] }, 2, id="sort1_indexed", ), pytest.param( "objects[\\cat]", {"objects": [{"cat": 2}, {"cat": 1}, {"cat": 3}]}, [[{"cat": 3}, {"cat": 2}, {"cat": 1}]], id="sort2", ), pytest.param( "objects[\\cat][-1].cat", {"objects": [{"cat": 2}, {"cat": 1}, {"cat": 3}]}, 1, id="sort2_indexed", ), pytest.param( "objects[/cow,\\cat]", { "objects": [ {"cat": 1, "cow": 2}, {"cat": 2, "cow": 1}, {"cat": 3, "cow": 1}, {"cat": 3, "cow": 3}, ] }, [ [ {"cat": 3, "cow": 1}, {"cat": 2, "cow": 1}, {"cat": 1, "cow": 2}, {"cat": 3, "cow": 3}, ] ], id="sort3", ), pytest.param( "objects[/cow,\\cat][0].cat", { "objects": [ {"cat": 1, "cow": 2}, {"cat": 2, "cow": 1}, {"cat": 3, "cow": 1}, {"cat": 3, "cow": 3}, ] }, 3, id="sort3_indexed", ), pytest.param( "objects[/cat.cow]", { "objects": [ {"cat": {"dog": 1, "cow": 2}}, {"cat": {"dog": 2, "cow": 1}}, {"cat": {"dog": 3, "cow": 3}}, ] }, [ [ {"cat": {"dog": 2, "cow": 1}}, {"cat": {"dog": 1, "cow": 2}}, {"cat": {"dog": 3, "cow": 3}}, ] ], id="sort4", ), pytest.param( "objects[/cat.cow][0].cat.dog", { "objects": [ {"cat": {"dog": 1, "cow": 2}}, {"cat": {"dog": 2, "cow": 1}}, {"cat": {"dog": 3, "cow": 3}}, ] }, 2, id="sort4_indexed", ), pytest.param( "objects[/cat.(cow,bow)]", { "objects": [ {"cat": {"dog": 1, "bow": 3}}, {"cat": {"dog": 2, "cow": 1}}, {"cat": {"dog": 2, "bow": 2}}, {"cat": {"dog": 3, "cow": 2}}, ] }, [ [ {"cat": {"dog": 2, "cow": 1}}, {"cat": {"dog": 2, "bow": 2}}, {"cat": {"dog": 3, "cow": 2}}, {"cat": {"dog": 1, "bow": 3}}, ] ], id="sort5_twofields", ), pytest.param( "objects[/cat.(cow,bow)][0].cat.dog", { "objects": [ {"cat": {"dog": 1, "bow": 3}}, {"cat": {"dog": 2, "cow": 1}}, {"cat": {"dog": 2, "bow": 2}}, {"cat": {"dog": 3, "cow": 2}}, ] }, 2, id="sort5_indexed", ), pytest.param("3 * 3", {}, [9], id="arithmetic_number_only"), pytest.param("$.foo * 10", {"foo": 4}, [40], id="arithmetic_mul1"), pytest.param("10 * $.foo", {"foo": 4}, [40], id="arithmetic_mul2"), pytest.param("$.foo * 10", {"foo": 4}, [40], id="arithmetic_mul3"), pytest.param("$.foo * 3", {"foo": "f"}, ["fff"], id="arithmetic_mul4"), pytest.param("foo * 3", {"foo": "f"}, ["foofoofoo"], id="arithmetic_mul5"), pytest.param("($.foo * 10 * $.foo) + 2", {"foo": 4}, [162], id="arithmetic_mul6"), pytest.param("$.foo * 10 * $.foo + 2", {"foo": 4}, [240], id="arithmetic_mul7"), pytest.param( "foo + bar", {"foo": "name", "bar": "node"}, ["foobar"], id="arithmetic_str0" ), pytest.param( 'foo + "_" + bar', {"foo": "name", "bar": "node"}, ["foo_bar"], id="arithmetic_str1", ), pytest.param( '$.foo + "_" + $.bar', {"foo": "name", "bar": "node"}, ["name_node"], id="arithmetic_str2", ), pytest.param( "$.foo + $.bar", {"foo": "name", "bar": "node"}, ["namenode"], id="arithmetic_str3", ), pytest.param( "foo.cow + bar.cow", {"foo": {"cow": "name"}, "bar": {"cow": "node"}}, ["namenode"], id="arithmetic_str4", ), pytest.param( "$.objects[*].cow * 2", {"objects": [{"cow": 1}, {"cow": 2}, {"cow": 3}]}, [2, 4, 6], id="arithmetic_list1", ), pytest.param( "$.objects[*].cow * $.objects[*].cow", {"objects": [{"cow": 1}, {"cow": 2}, {"cow": 3}]}, [1, 4, 9], id="arithmetic_list2", ), pytest.param( "$.objects[*].cow * $.objects2[*].cow", {"objects": [{"cow": 1}, {"cow": 2}, {"cow": 3}], "objects2": [{"cow": 5}]}, [], id="arithmetic_list_err1", ), pytest.param('$.objects * "foo"', {"objects": []}, [], id="arithmetic_err1"), pytest.param('"bar" * "foo"', {}, [], id="arithmetic_err2"), pytest.param( "payload.metrics[?(@.name='cpu.frequency')].value * 100", { "payload": { "metrics": [ { "timestamp": "2013-07-29T06:51:34.472416", "name": "cpu.frequency", "value": 1600, "source": "libvirt.LibvirtDriver", }, { "timestamp": "2013-07-29T06:51:34.472416", "name": "cpu.user.time", "value": 17421440000000, "source": "libvirt.LibvirtDriver", }, ] } }, [160000], id="real_life_example1", ), pytest.param( "payload.(id|(resource.id))", {"payload": {"id": "foobar"}}, ["foobar"], id="real_life_example2", ), pytest.param( "payload.id|(resource.id)", {"payload": {"resource": {"id": "foobar"}}}, ["foobar"], id="real_life_example3", ), pytest.param( "payload.id|(resource.id)", {"payload": {"id": "yes", "resource": {"id": "foobar"}}}, ["yes", "foobar"], id="real_life_example4", ), pytest.param( "payload.`sub(/(foo\\\\d+)\\\\+(\\\\d+bar)/, \\\\2-\\\\1)`", {"payload": "foo5+3bar"}, ["3bar-foo5"], id="sub1", ), pytest.param( "payload.`sub(/foo\\\\+bar/, repl)`", {"payload": "foo+bar"}, ["repl"], id="sub2", ), pytest.param("payload.`str()`", {"payload": 1}, ["1"], id="str1"), pytest.param( "payload.`split(-, 2, -1)`", {"payload": "foo-bar-cat-bow"}, ["cat"], id="split1", ), pytest.param( "payload.`split(-, 2, 2)`", {"payload": "foo-bar-cat-bow"}, ["cat-bow"], id="split2", ), pytest.param( "foo[?(@.baz==1)]", {"foo": [{"baz": 1}, {"baz": 2}]}, [{"baz": 1}], id="bug-#2-correct", ), pytest.param( "foo[*][?(@.baz==1)]", {"foo": [{"baz": 1}, {"baz": 2}]}, [], id="bug-#2-wrong" ), pytest.param( "foo[?flag = true].color", { "foo": [ {"color": "blue", "flag": True}, {"color": "green", "flag": False}, ] }, ["blue"], id="boolean-filter-true", ), pytest.param( "foo[?flag = false].color", { "foo": [ {"color": "blue", "flag": True}, {"color": "green", "flag": False}, ] }, ["green"], id="boolean-filter-false", ), pytest.param( "foo[?flag = true].color", { "foo": [ {"color": "blue", "flag": True}, {"color": "green", "flag": 2}, {"color": "red", "flag": "hi"}, ] }, ["blue"], id="boolean-filter-other-datatypes-involved", ), pytest.param( 'foo[?flag = "true"].color', { "foo": [ {"color": "blue", "flag": True}, {"color": "green", "flag": "true"}, ] }, ["green"], id="boolean-filter-string-true-string-literal", ), ) @pytest.mark.parametrize("path, data, expected_values", test_cases) def test_values(path, data, expected_values): results = parser.parse(path).find(data) assert_value_equality(results, expected_values) def test_invalid_hyphenation_in_key(): # This test is almost copied-and-pasted directly from `test_jsonpath.py`. # However, the parsers generate different exceptions for this syntax error. # This discrepancy needs to be resolved. with pytest.raises(JsonPathParserError): parser.parse("foo.-baz") ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1699968179.0 jsonpath-ng-1.6.1/tests/test_lexer.py0000664000175100017510000000326314524672263016754 0ustar00mmiormmiorimport pytest from jsonpath_ng.lexer import JsonPathLexer, JsonPathLexerError token_test_cases = ( ("$", (("$", "$"),)), ('"hello"', (("hello", "ID"),)), ("'goodbye'", (("goodbye", "ID"),)), ("'doublequote\"'", (('doublequote"', "ID"),)), (r'"doublequote\""', (('doublequote"', "ID"),)), (r"'singlequote\''", (("singlequote'", "ID"),)), ('"singlequote\'"', (("singlequote'", "ID"),)), ("fuzz", (("fuzz", "ID"),)), ("1", ((1, "NUMBER"),)), ("45", ((45, "NUMBER"),)), ("-1", ((-1, "NUMBER"),)), (" -13 ", ((-13, "NUMBER"),)), ('"fuzz.bang"', (("fuzz.bang", "ID"),)), ("fuzz.bang", (("fuzz", "ID"), (".", "."), ("bang", "ID"))), ("fuzz.*", (("fuzz", "ID"), (".", "."), ("*", "*"))), ("fuzz..bang", (("fuzz", "ID"), ("..", "DOUBLEDOT"), ("bang", "ID"))), ("&", (("&", "&"),)), ("@", (("@", "ID"),)), ("`this`", (("this", "NAMED_OPERATOR"),)), ("|", (("|", "|"),)), ("where", (("where", "WHERE"),)), ) @pytest.mark.parametrize("string, expected_token_info", token_test_cases) def test_lexer(string, expected_token_info): lexer = JsonPathLexer(debug=True) tokens = list(lexer.tokenize(string)) assert len(tokens) == len(expected_token_info) for token, (expected_value, expected_type) in zip(tokens, expected_token_info): assert token.type == expected_type assert token.value == expected_value invalid_token_test_cases = ( "'\"", "\"'", '`"', "`'", '"`', "'`", "?", "$.foo.bar.#", ) @pytest.mark.parametrize("string", invalid_token_test_cases) def test_lexer_errors(string): with pytest.raises(JsonPathLexerError): list(JsonPathLexer().tokenize(string)) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1699968179.0 jsonpath-ng-1.6.1/tests/test_parser.py0000664000175100017510000000224514524672263017130 0ustar00mmiormmiorimport pytest from jsonpath_ng.jsonpath import Child, Descendants, Fields, Index, Slice, Where from jsonpath_ng.lexer import JsonPathLexer from jsonpath_ng.parser import JsonPathParser # Format: (string, expected_object) parser_test_cases = ( # # Atomic # ------ # ("foo", Fields("foo")), ("*", Fields("*")), ("baz,bizzle", Fields("baz", "bizzle")), ("[1]", Index(1)), ("[1:]", Slice(start=1)), ("[:]", Slice()), ("[*]", Slice()), ("[:2]", Slice(end=2)), ("[1:2]", Slice(start=1, end=2)), ("[5:-2]", Slice(start=5, end=-2)), # # Nested # ------ # ("foo.baz", Child(Fields("foo"), Fields("baz"))), ("foo.baz,bizzle", Child(Fields("foo"), Fields("baz", "bizzle"))), ("foo where baz", Where(Fields("foo"), Fields("baz"))), ("foo..baz", Descendants(Fields("foo"), Fields("baz"))), ("foo..baz.bing", Descendants(Fields("foo"), Child(Fields("baz"), Fields("bing")))), ) @pytest.mark.parametrize("string, expected_object", parser_test_cases) def test_parser(string, expected_object): parser = JsonPathParser(lexer_class=lambda: JsonPathLexer()) assert parser.parse(string) == expected_object