[Git][debian-gis-team/jsonpath-ng][upstream] New upstream version 1.6.0
Antonio Valentino (@antonio.valentino)
gitlab at salsa.debian.org
Sat Sep 16 14:35:12 BST 2023
Antonio Valentino pushed to branch upstream at Debian GIS Project / jsonpath-ng
Commits:
cf3764a5 by Antonio Valentino at 2023-09-16T13:18:12+00:00
New upstream version 1.6.0
- - - - -
17 changed files:
- + LICENSE
- MANIFEST.in
- PKG-INFO
- README.rst
- jsonpath_ng.egg-info/PKG-INFO
- jsonpath_ng.egg-info/SOURCES.txt
- jsonpath_ng.egg-info/entry_points.txt
- jsonpath_ng.egg-info/requires.txt
- jsonpath_ng/__init__.py
- jsonpath_ng/ext/filter.py
- jsonpath_ng/ext/string.py
- jsonpath_ng/jsonpath.py
- jsonpath_ng/lexer.py
- jsonpath_ng/parser.py
- setup.py
- tests/test_jsonpath.py
- tests/test_jsonpath_rw_ext.py
Changes:
=====================================
LICENSE
=====================================
@@ -0,0 +1,202 @@
+
+ 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.
=====================================
MANIFEST.in
=====================================
@@ -1 +1,2 @@
recursive-include tests *.json *.py
+include LICENSE
=====================================
PKG-INFO
=====================================
@@ -1,349 +1,360 @@
-Metadata-Version: 1.1
+Metadata-Version: 2.1
Name: jsonpath-ng
-Version: 1.5.3
+Version: 1.6.0
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 at aparicio.me
License: Apache 2.0
-Description: 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 removes nodes in the tree.
-
- About
- -----
-
- This library provides a robust and significantly extended implementation
- of JSONPath for Python. It is tested with CPython 2.6, 2.7 & 3.x.
-
- 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']
-
- # 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 currently
- 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
- ----------
-
- +--------------+----------------------------------------------+
- | name | Example |
- +==============+==============================================+
- | len | - $.objects.`len` |
- +--------------+----------------------------------------------+
- | sub | - $.field.`sub(/foo\\\\+(.*)/, \\\\1)` |
- +--------------+----------------------------------------------+
- | 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)] |
- +--------------+----------------------------------------------+
- | 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 <http://goessner.net/articles/JSONPath/>`__ 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 <https://github.com/dabeaz/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 <https://github.com/kennknowles>`__
- (`@kennknowles <https://twitter.com/KennKnowles>`__)
- - `Tomas Aparicio <https://github.com/h2non>`
-
- with the help of patches submitted by `these contributors <https://github.com/kennknowles/python-jsonpath-ng/graphs/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://travis-ci.org/h2non/jsonpath-ng.svg?branch=master
- :target: https://travis-ci.org/h2non/jsonpath-ng
- .. |PyPI| image:: https://img.shields.io/pypi/v/jsonpath-ng.svg?maxAge=2592000?style=flat-square
- :target: https://pypi.python.org/pypi/jsonpath-ng
- .. |Documentation Status| image:: https://img.shields.io/badge/docs-latest-green.svg?style=flat
- :target: http://jsonpath-ng.readthedocs.io/en/latest/?badge=latest
-
-Platform: UNKNOWN
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: Apache Software License
-Classifier: Programming Language :: Python :: 2.7
Classifier: Programming Language :: Python :: 3
-Classifier: Programming Language :: Python :: 3.5
-Classifier: Programming Language :: Python :: 3.6
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
+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 removes nodes in the tree.
+
+About
+-----
+
+This library provides a robust and significantly extended implementation
+of JSONPath for Python. It is tested with CPython 2.6, 2.7 & 3.x.
+
+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']
+
+ # 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 currently
+ 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 <http://goessner.net/articles/JSONPath/>`__ 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 <https://github.com/dabeaz/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 <https://github.com/kennknowles>`__
+ (`@kennknowles <https://twitter.com/KennKnowles>`__)
+- `Tomas Aparicio <https://github.com/h2non>`
+
+with the help of patches submitted by `these contributors <https://github.com/kennknowles/python-jsonpath-ng/graphs/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
=====================================
README.rst
=====================================
@@ -187,29 +187,42 @@ Extras
Extensions
----------
-+--------------+----------------------------------------------+
-| name | Example |
-+==============+==============================================+
-| len | - $.objects.`len` |
-+--------------+----------------------------------------------+
-| sub | - $.field.`sub(/foo\\\\+(.*)/, \\\\1)` |
-+--------------+----------------------------------------------+
-| 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)] |
-+--------------+----------------------------------------------+
-| arithmetic | - $.foo + "_" + $.bar |
-| (-+*/) | - $.foo * 12 |
-| | - $.objects[*].cow + $.objects[*].cat |
-+--------------+----------------------------------------------+
+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
---------------------------
@@ -228,10 +241,10 @@ Example with data::
'fish': 'bar'
}
-| **cow + fish** returns **cowfish**
-| **$.cow + $.fish** returns **foobar**
-| **$.cow + "_" + $.fish** returns **foo_bar**
-| **$.cow + "_" + fish** returns **foo_fish**
+| ``cow + fish`` returns ``cowfish``
+| ``$.cow + $.fish`` returns ``foobar``
+| ``$.cow + "_" + $.fish`` returns ``foo_bar``
+| ``$.cow + "_" + fish`` returns ``foo_fish``
About arithmetic and list
-------------------------
@@ -245,7 +258,7 @@ Example with data::
{'cow': 4, 'cat': 6}
]}
-| **$.objects[\*].cow + $.objects[\*].cat** returns **[6, 9]**
+| ``$.objects[\*].cow + $.objects[\*].cat`` returns ``[6, 9]``
More to explore
---------------
@@ -322,9 +335,7 @@ limitations under the License.
.. |PyPi downloads| image:: https://pypip.in/d/jsonpath-ng/badge.png
:target: https://pypi.python.org/pypi/jsonpath-ng
-.. |Build Status| image:: https://travis-ci.org/h2non/jsonpath-ng.svg?branch=master
- :target: https://travis-ci.org/h2non/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
-.. |Documentation Status| image:: https://img.shields.io/badge/docs-latest-green.svg?style=flat
- :target: http://jsonpath-ng.readthedocs.io/en/latest/?badge=latest
=====================================
jsonpath_ng.egg-info/PKG-INFO
=====================================
@@ -1,349 +1,360 @@
-Metadata-Version: 1.1
+Metadata-Version: 2.1
Name: jsonpath-ng
-Version: 1.5.3
+Version: 1.6.0
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 at aparicio.me
License: Apache 2.0
-Description: 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 removes nodes in the tree.
-
- About
- -----
-
- This library provides a robust and significantly extended implementation
- of JSONPath for Python. It is tested with CPython 2.6, 2.7 & 3.x.
-
- 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']
-
- # 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 currently
- 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
- ----------
-
- +--------------+----------------------------------------------+
- | name | Example |
- +==============+==============================================+
- | len | - $.objects.`len` |
- +--------------+----------------------------------------------+
- | sub | - $.field.`sub(/foo\\\\+(.*)/, \\\\1)` |
- +--------------+----------------------------------------------+
- | 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)] |
- +--------------+----------------------------------------------+
- | 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 <http://goessner.net/articles/JSONPath/>`__ 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 <https://github.com/dabeaz/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 <https://github.com/kennknowles>`__
- (`@kennknowles <https://twitter.com/KennKnowles>`__)
- - `Tomas Aparicio <https://github.com/h2non>`
-
- with the help of patches submitted by `these contributors <https://github.com/kennknowles/python-jsonpath-ng/graphs/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://travis-ci.org/h2non/jsonpath-ng.svg?branch=master
- :target: https://travis-ci.org/h2non/jsonpath-ng
- .. |PyPI| image:: https://img.shields.io/pypi/v/jsonpath-ng.svg?maxAge=2592000?style=flat-square
- :target: https://pypi.python.org/pypi/jsonpath-ng
- .. |Documentation Status| image:: https://img.shields.io/badge/docs-latest-green.svg?style=flat
- :target: http://jsonpath-ng.readthedocs.io/en/latest/?badge=latest
-
-Platform: UNKNOWN
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: Apache Software License
-Classifier: Programming Language :: Python :: 2.7
Classifier: Programming Language :: Python :: 3
-Classifier: Programming Language :: Python :: 3.5
-Classifier: Programming Language :: Python :: 3.6
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
+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 removes nodes in the tree.
+
+About
+-----
+
+This library provides a robust and significantly extended implementation
+of JSONPath for Python. It is tested with CPython 2.6, 2.7 & 3.x.
+
+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']
+
+ # 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 currently
+ 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 <http://goessner.net/articles/JSONPath/>`__ 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 <https://github.com/dabeaz/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 <https://github.com/kennknowles>`__
+ (`@kennknowles <https://twitter.com/KennKnowles>`__)
+- `Tomas Aparicio <https://github.com/h2non>`
+
+with the help of patches submitted by `these contributors <https://github.com/kennknowles/python-jsonpath-ng/graphs/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
=====================================
jsonpath_ng.egg-info/SOURCES.txt
=====================================
@@ -1,3 +1,4 @@
+LICENSE
MANIFEST.in
README.rst
setup.py
=====================================
jsonpath_ng.egg-info/entry_points.txt
=====================================
@@ -1,3 +1,2 @@
[console_scripts]
jsonpath_ng = jsonpath_ng.bin.jsonpath:entry_point
-
=====================================
jsonpath_ng.egg-info/requires.txt
=====================================
@@ -1,3 +1 @@
ply
-decorator
-six
=====================================
jsonpath_ng/__init__.py
=====================================
@@ -3,4 +3,4 @@ from .parser import parse # noqa
# Current package version
-__version__ = '1.5.3'
+__version__ = '1.6.0'
=====================================
jsonpath_ng/ext/filter.py
=====================================
@@ -13,7 +13,6 @@
import operator
import re
-from six import moves
from .. import JSONPath, DatumInContext, Index
@@ -49,7 +48,7 @@ class Filter(JSONPath):
return []
return [DatumInContext(datum.value[i], path=Index(i), context=datum)
- for i in moves.range(0, len(datum.value))
+ for i in range(0, len(datum.value))
if (len(self.expressions) ==
len(list(filter(lambda x: x.find(datum.value[i]),
self.expressions))))]
=====================================
jsonpath_ng/ext/string.py
=====================================
@@ -15,9 +15,9 @@ import re
from .. import DatumInContext, This
-SUB = re.compile("sub\(/(.*)/,\s+(.*)\)")
-SPLIT = re.compile("split\((.),\s+(\d+),\s+(\d+|-1)\)")
-STR = re.compile("str\(\)")
+SUB = re.compile(r"sub\(/(.*)/,\s+(.*)\)")
+SPLIT = re.compile(r"split\((.),\s+(\d+),\s+(\d+|-1)\)")
+STR = re.compile(r"str\(\)")
class DefintionInvalid(Exception):
=====================================
jsonpath_ng/jsonpath.py
=====================================
@@ -1,9 +1,9 @@
-from __future__ import unicode_literals, print_function, absolute_import, division, generators, nested_scopes
+from __future__ import (absolute_import, division, generators, nested_scopes,
+ print_function, unicode_literals)
+
import logging
-import six
-from six.moves import xrange
from itertools import * # noqa
-from .exceptions import JSONPathError
+from jsonpath_ng.lexer import JsonPathLexer
# Get logger name
logger = logging.getLogger(__name__)
@@ -220,6 +220,9 @@ class Root(JSONPath):
def __eq__(self, other):
return isinstance(other, Root)
+ def __hash__(self):
+ return hash('$')
+
class This(JSONPath):
"""
@@ -244,6 +247,9 @@ class This(JSONPath):
def __eq__(self, other):
return isinstance(other, This)
+ def __hash__(self):
+ return hash('this')
+
class Child(JSONPath):
"""
@@ -302,6 +308,9 @@ class Child(JSONPath):
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):
"""
@@ -323,6 +332,9 @@ class Parent(JSONPath):
def __repr__(self):
return 'Parent()'
+ def __hash__(self):
+ return hash('parent')
+
class Where(JSONPath):
"""
@@ -357,6 +369,9 @@ class Where(JSONPath):
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
@@ -469,6 +484,9 @@ class Descendants(JSONPath):
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):
"""
@@ -490,6 +508,12 @@ class Union(JSONPath):
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.
@@ -511,6 +535,12 @@ class Intersect(JSONPath):
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):
"""
@@ -588,7 +618,14 @@ class Fields(JSONPath):
return data
def __str__(self):
- return ','.join(map(str, self.fields))
+ # 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)))
@@ -596,6 +633,9 @@ class Fields(JSONPath):
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):
"""
@@ -662,6 +702,9 @@ class Index(JSONPath):
pad = self.index - len(value) + 1
value += [{} for __ in range(pad)]
+ def __hash__(self):
+ return hash(self.index)
+
class Slice(JSONPath):
"""
@@ -700,13 +743,13 @@ class Slice(JSONPath):
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, six.integer_types) or isinstance(datum.value, six.string_types)):
+ 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 == None and self.end == None and self.step == None:
- return [DatumInContext(datum.value[i], path=Index(i), context=datum) for i in xrange(0, len(datum.value))]
+ 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]]
@@ -728,7 +771,7 @@ class Slice(JSONPath):
return data
def __str__(self):
- if self.start == None and self.end == None and self.step == None:
+ if self.start is None and self.end is None and self.step is None:
return '[*]'
else:
return '[%s%s%s]' % (self.start or '',
@@ -741,6 +784,9 @@ class Slice(JSONPath):
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_):
"""
=====================================
jsonpath_ng/lexer.py
=====================================
@@ -16,7 +16,7 @@ class JsonPathLexer(object):
def __init__(self, debug=False):
self.debug = debug
- if self.__doc__ == None:
+ 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):
@@ -31,7 +31,8 @@ class JsonPathLexer(object):
while True:
t = new_lexer.token()
- if t is None: break
+ if t is None:
+ break
t.col = t.lexpos - new_lexer.latest_newline
yield t
=====================================
jsonpath_ng/parser.py
=====================================
@@ -5,6 +5,7 @@ from __future__ import (
generators,
nested_scopes,
)
+import logging
import sys
import os.path
@@ -55,7 +56,8 @@ class JsonPathParser(object):
parsing_table_module = '_'.join([module_name, start_symbol, 'parsetab'])
- # And we regenerate the parse table every time; it doesn't actually take that long!
+ # 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,
=====================================
setup.py
=====================================
@@ -4,9 +4,9 @@ import setuptools
setuptools.setup(
name='jsonpath-ng',
- version='1.5.3',
+ version='1.6.0',
description=(
- 'A final implementation of JSONPath for Python that aims to be '
+ '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.'
),
@@ -23,17 +23,17 @@ setuptools.setup(
},
test_suite='tests',
install_requires=[
- 'ply', 'decorator', 'six'
+ 'ply'
],
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
- 'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
- 'Programming Language :: Python :: 3.5',
- 'Programming Language :: Python :: 3.6',
- 'Programming Language :: Python :: 3.7',
- 'Programming Language :: Python :: 3.8',
+ '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'
],
)
=====================================
tests/test_jsonpath.py
=====================================
@@ -136,7 +136,7 @@ class TestJsonPath(unittest.TestCase):
def test_slice_value(self):
self.check_cases([('[*]', [1, 2, 3], [1, 2, 3]),
- ('[*]', xrange(1, 4), [1, 2, 3]),
+ ('[*]', range(1, 4), [1, 2, 3]),
('[1:]', [1, 2, 3, 4], [2, 3, 4]),
('[:2]', [1, 2, 3, 4], [1, 2])])
@@ -183,6 +183,7 @@ class TestJsonPath(unittest.TestCase):
for string, data, target in test_cases:
print('parse("%s").find(%s).paths =?= %s' % (string, data, target))
+ assert hash(parse(string)) == hash(parse(string))
result = parse(string).find(data)
if isinstance(target, list):
assert [str(r.full_path) for r in result] == target
@@ -232,6 +233,8 @@ class TestJsonPath(unittest.TestCase):
def test_descendants_paths(self):
self.check_paths([('foo..baz', {'foo': {'baz': 1, 'bing': {'baz': 2}}}, ['foo.baz', 'foo.bing.baz'] )])
+ def test_literals_in_field_names(self):
+ self.check_paths([("A.'a.c'", {'A' : {'a.c': 'd'}}, ["A.'a.c'"])])
#
# Check the "auto_id_field" feature
=====================================
tests/test_jsonpath_rw_ext.py
=====================================
@@ -21,14 +21,23 @@ Tests for `jsonpath_ng_ext` module.
from jsonpath_ng import jsonpath # For setting the global auto_id_field flag
from oslotest import base
-from six import moves
-import testscenarios
from jsonpath_ng.ext import parser
-class Testjsonpath_ng_ext(testscenarios.WithScenarios,
- base.BaseTestCase):
+# Example from https://docs.pytest.org/en/7.1.x/example/parametrize.html#a-quick-port-of-testscenarios
+def pytest_generate_tests(metafunc):
+ idlist = []
+ argvalues = []
+ for scenario in metafunc.cls.scenarios:
+ idlist.append(scenario[0])
+ items = scenario[1].items()
+ argnames = [x[0] for x in items]
+ argvalues.append([x[1] for x in items])
+ metafunc.parametrize(argnames, argvalues, ids=idlist, scope="class")
+
+
+class Testjsonpath_ng_ext:
scenarios = [
('sorted_list', dict(string='objects.`sorted`',
data={'objects': ['alpha', 'gamma', 'beta']},
@@ -126,14 +135,14 @@ class Testjsonpath_ng_ext(testscenarios.WithScenarios,
{'cat': 2, 'cow': 1},
{'cat': 3, 'cow': 3}]},
target=2)),
- ('sort2', dict(string='objects[\cat]',
+ ('sort2', dict(string='objects[\\cat]',
data={'objects': [{'cat': 2}, {'cat': 1}, {'cat': 3}]},
target=[[{'cat': 3}, {'cat': 2}, {'cat': 1}]])),
- ('sort2_indexed', dict(string='objects[\cat][-1].cat',
+ ('sort2_indexed', dict(string='objects[\\cat][-1].cat',
data={'objects': [{'cat': 2}, {'cat': 1},
{'cat': 3}]},
target=1)),
- ('sort3', dict(string='objects[/cow,\cat]',
+ ('sort3', dict(string='objects[/cow,\\cat]',
data={'objects': [{'cat': 1, 'cow': 2},
{'cat': 2, 'cow': 1},
{'cat': 3, 'cow': 1},
@@ -142,7 +151,7 @@ class Testjsonpath_ng_ext(testscenarios.WithScenarios,
{'cat': 2, 'cow': 1},
{'cat': 1, 'cow': 2},
{'cat': 3, 'cow': 3}]])),
- ('sort3_indexed', dict(string='objects[/cow,\cat][0].cat',
+ ('sort3_indexed', dict(string='objects[/cow,\\cat][0].cat',
data={'objects': [{'cat': 1, 'cow': 2},
{'cat': 2, 'cow': 1},
{'cat': 3, 'cow': 1},
@@ -334,17 +343,17 @@ class Testjsonpath_ng_ext(testscenarios.WithScenarios,
)),
]
- def test_fields_value(self):
+ def test_fields_value(self, string, data, target):
jsonpath.auto_id_field = None
- result = parser.parse(self.string, debug=True).find(self.data)
- if isinstance(self.target, list):
- self.assertEqual(self.target, [r.value for r in result])
- elif isinstance(self.target, set):
- self.assertEqual(self.target, set([r.value for r in result]))
- elif isinstance(self.target, (int, float)):
- self.assertEqual(self.target, result[0].value)
+ result = parser.parse(string, debug=True).find(data)
+ if isinstance(target, list):
+ assert target == [r.value for r in result]
+ elif isinstance(target, set):
+ assert target == set([r.value for r in result])
+ elif isinstance(target, (int, float)):
+ assert target == result[0].value
else:
- self.assertEqual(self.target, result[0].value)
+ assert target == result[0].value
# NOTE(sileht): copy of tests/test_jsonpath.py
# to ensure we didn't break jsonpath_ng
@@ -406,7 +415,7 @@ class TestJsonPath(base.BaseTestCase):
def test_slice_value(self):
self.check_cases([('[*]', [1, 2, 3], [1, 2, 3]),
- ('[*]', moves.range(1, 4), [1, 2, 3]),
+ ('[*]', range(1, 4), [1, 2, 3]),
('[1:]', [1, 2, 3, 4], [2, 3, 4]),
('[:2]', [1, 2, 3, 4], [1, 2])])
View it on GitLab: https://salsa.debian.org/debian-gis-team/jsonpath-ng/-/commit/cf3764a5a039fc1bdb021c02d137ab054b68a678
--
View it on GitLab: https://salsa.debian.org/debian-gis-team/jsonpath-ng/-/commit/cf3764a5a039fc1bdb021c02d137ab054b68a678
You're receiving this email because of your account on salsa.debian.org.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://alioth-lists.debian.net/pipermail/pkg-grass-devel/attachments/20230916/30aefd88/attachment-0001.htm>
More information about the Pkg-grass-devel
mailing list