h2non/jsonpath-ng
h2non/jsonpath-ng được TopGit xếp vào nhóm dự án backend, với 739 sao trên GitHub, viết chủ yếu bằng Python. Finally, a JSONPath implementation for Python that aims to be standard compliant. Enjoy!
Tóm tắt dựng từ metadata GitHub của chính dự án — chưa có bài review TopGit. Trang sẽ tự động cập nhật khi bài review đầy đủ được xuất bản.
TopGit viết bài đầy đủ cho repo có nhiều sao nhất và được yêu cầu nhiều nhất. Trang này là snapshot trong thời gian chờ — xem README gốc ở tab READ ME.
Snapshot
Cộng tác viên hàng đầu
Xem cộng tác viên hàng đầu
Python JSONPath Next-Generation
An implementation of JSONPath for Python that aims to be standards compliant,
as defined in RFC 9535_.
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.
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:: pycon
>>> 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 one', 'number two']
# You can also build expressions directly quite easily
>>> from jsonpath_ng.jsonpath import Fields
>>> from jsonpath_ng.jsonpath import Wildcard
>>> parse('foo[*].baz') == Fields('foo').child(Wildcard()).child(Fields('baz'))
True
Using the extended parser:
.. code:: pycon
>>> from jsonpath_ng.ext import parse
>>> jsonpath_expr = parse('foo[*].baz')
JSONPath Syntax
The JSONPath syntax supported by this library includes some additional features.
In particular, some new operators such as 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 wherenot jsonpath2 | Any nodes matching jsonpath1 with a child not matching 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 |
+-------------------------+-------------------------------------------------------------------------------------+
Array specifiers ( idx ):
+-------------------------------------------------------+------------------------------------------------------------+
| Syntax | Meaning |
+=======================================================+============================================================+
| [\ n\ ] | array index (may be comma-separated list) |
+-------------------------------------------------------+------------------------------------------------------------+
| [\ start\ ?:\ end\ ?:\ step\ ?] | array slicing; start, end, and step are all optional |
+-------------------------------------------------------+------------------------------------------------------------+
| [*] | 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(Wildcard(), Fields('subfield'))Descendants(jsonpath, jsonpath)
Extras
- Path data: The result of
JsonPath.findprovide 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_fieldto 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 usesthis. 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``` | +--------------+--------------------------------------------------+ | keys | - $.objects.keys``` | +--------------+--------------------------------------------------+ | str | - ``$.field.str() | +--------------+--------------------------------------------------+ | sub | - ``$.field.`sub(/foo\\+(.*)/, \\1) |
| | - $.field.`sub(/regex/, replacement)``` | +--------------+--------------------------------------------------+ | split | - $.field.split(+, 2, -1)``` | | | - ``$.field.split(",", , -1) | | | - ``$.field.`split(' ', -1, -1) |
| | - $.field.`split(sep, segment, 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[[email protected] > 5 && @.cat < 2] |
| | - $.objects[[email protected] > 5 || @.cat < 2] |
| | - $.objects[[email protected]_field] |
| | |
| | Supported operators: |
| | |
| | - Equality: ==, =, != |
| | - Comparison: >, >=, <, <= |
| | - Regex match: =~ |
| | - Existence negation: ! |
| | |
| | Combine criteria with && (and) and || |
| | (or). && binds more tightly than ||, |
| | and parentheses group. |
| | |
| | Properties can be compared to literal values |
| | or to singular queries, such as @.a == $.b. |
+--------------+--------------------------------------------------+
| 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't 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:
.. code-block:: json
{
"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:
.. code-block:: json
{"objects": [
{"cow": 2, "cat": 3},
{"cow": 4, "cat": 6}
]}
| $.objects[\*].cow + $.objects[\*].cat returns [6, 9]
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)
Contributors
This package is authored and maintained by:
Kenn Knowles <https://github.com/kennknowles>__Tomas Aparicio <https://github.com/h2non>__Kurt McKee <https://github.com/kurtmckee>__
with the help of patches submitted by these contributors <https://github.com/jsonpath-ng/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.
.. Links
.. -----
.. _RFC 9535: https://www.rfc-editor.org/info/rfc9535/
.. _jsonpath-rw: https://github.com/kennknowles/python-jsonpath-rw
.. _jsonpath-rw-ext: https://pypi.python.org/pypi/jsonpath-rw-ext/
Repo liên quan
Awesome Python is a curated list maintained at vinta/awesome-python that groups Python frameworks, libraries, tools, and other resources into 14 categories, from AI & ML to Security and Other. The README calls it an opinionated guide rather than an exhaustive one, and points readers to a companion site, awesome-python.com, for searching and filtering entries instead of scrolling the raw file.
The Algorithms - Python is an open-source collection of algorithm implementations written in Python, maintained by the TheAlgorithms organization on GitHub. The README frames the whole project as a teaching resource: the code exists to illustrate concepts, can run slower than Python's built-in equivalents, and is indexed in DIRECTORY.md for browsing. It's MIT licensed and available on GitHub.
HelloGitHub is a curated GitHub repository from 521xueweihan that publishes a monthly digest of entry-level open source projects, open source books, practical projects, and enterprise-level projects, aimed mainly at Chinese-reading developers new to open source. The README says issues go out on the 28th of each month, and the repo's own issue table runs past number 124, with reader recommendations and self-nominations accepted through a documented contribution process.
CS-Notes is a GitHub repository maintained by CyC2018 that collects Chinese-language study notes across ten topic areas: algorithms, operating systems, networking, object-oriented design, databases, Java, system design, tools, coding practice, and an afterword. It links each topic to standalone markdown files instead of writing everything inline, and the README says most of the content is original work rather than material copied from elsewhere.
Trả lời nhanh
Đọc thêm về h2non/jsonpath-ng ở đâu?
Trang TopGit này là một snapshot — tab "Readme" hiển thị nguyên văn README của repo (đã bỏ link, giữ ảnh). Repo GitHub ở github.com/h2non/jsonpath-ng là nguồn chính thức.
h2non/jsonpath-ng có những chủ đề gì?
GitHub topics của h2non/jsonpath-ng: "json", "jsonpath", "python". TopGit xếp repo vào nhóm Backend.
h2non/jsonpath-ng có phải mã nguồn mở không?
Có — h2non/jsonpath-ng phát hành theo license Apache-2.0, nghĩa là mã nguồn mở để đọc, fork và (tùy license) tái sử dụng. Mã: github.com/h2non/jsonpath-ng.
h2non/jsonpath-ng có trang demo không?
Dự án có trang chủ ở https://jsonpath-ng.readthedocs.io/. Tab "Readme" ở trang này thường có ảnh chụp và hướng dẫn bắt đầu nhanh.
h2non/jsonpath-ng còn đang phát triển không?
Commit gần nhất trên h2non/jsonpath-ng là 4 ngày trước (theo timestamp GitHub). Repo có 137 fork — một chỉ báo về mức độ quan tâm của cộng đồng.
h2non/jsonpath-ng dùng license gì?
h2non/jsonpath-ng phát hành theo license Apache-2.0. Nên mở file LICENSE trên GitHub để xác nhận — license metadata đôi khi lệch với thực tế dự án.
Đọc đầy đủ README ở tab phía trên.
Chưa chắc jsonpath-ng có hợp với bạn?
Để ChatGPT, Claude hoặc Perplexity tìm hiểu giúp — bấm bên dưới và xem AI nói gì về jsonpath-ng.