跳至主要内容

JSON匹配表达式

项目描述

JMESPath

https://badges.gitter.im/JoinChat.svg

JMESPath(发音为“james path”)允许您声明性地指定如何从JSON文档中提取元素。

例如,给定此文档

{"foo": {"bar": "baz"}}

JMESPath表达式foo.bar将返回“baz”。

JMESPath还支持

引用列表中的元素。给定以下数据

{"foo": {"bar": ["one", "two"]}}

表达式: foo.bar[0]将返回“one”。您也可以使用*语法引用列表中的所有项

{"foo": {"bar": [{"name": "one"}, {"name": "two"}]}}

表达式:foo.bar[*].name将返回[“one”,“two”]。还支持负索引(-1指向列表中的最后一个元素)。给定上面的数据,表达式foo.bar[-1].name将返回“two”。

*也可以用于哈希类型

{"foo": {"bar": {"name": "one"}, "baz": {"name": "two"}}}

表达式:foo.*.name将返回[“one”,“two”]。

安装

您可以使用以下命令从PyPI安装JMESPath

pip install jmespath

API

《jmespath.py》库有两个操作Python数据结构的函数。您可以使用 search 函数,并传入jmespath表达式和数据。

>>> import jmespath
>>> path = jmespath.search('foo.bar', {'foo': {'bar': 'baz'}})
'baz'

re 模块类似,您可以使用 compile 函数编译JMESPath表达式,并使用此解析后的表达式执行重复搜索。

>>> import jmespath
>>> expression = jmespath.compile('foo.bar')
>>> expression.search({'foo': {'bar': 'baz'}})
'baz'
>>> expression.search({'foo': {'bar': 'other'}})
'other'

如果您打算使用相同的jmespath表达式搜索多个文档,这将非常有用。这可以避免每次搜索新文档时都需要重新解析JMESPath表达式。

选项

您可以为 jmespath.Options 提供一个实例来控制如何评估JMESPath表达式。使用 Options 实例的最常见场景是您希望得到字典键的有序输出。为此,您可以使用以下任一选项

>>> import jmespath
>>> jmespath.search('{a: a, b: b}',
...                 mydata,
...                 jmespath.Options(dict_cls=collections.OrderedDict))


>>> import jmespath
>>> parsed = jmespath.compile('{a: a, b: b}')
>>> parsed.search(mydata,
...               jmespath.Options(dict_cls=collections.OrderedDict))

自定义函数

JMESPath语言有许多内置函数,但也可能添加您自己的自定义函数。请注意,jmespath.py中的自定义函数支持是实验性的,API可能会根据反馈而更改。

如果您有一个有用的自定义函数,请考虑将其提交给jmespath.site,并提出将其添加到JMESPath语言的建议。 您可以在此处提交建议。

创建自定义函数

  • 创建 jmespath.functions.Functions 的子类。

  • 创建一个名为 _func_<your function name> 的方法。

  • 应用 jmespath.functions.signature 装饰器,该装饰器指示函数参数的预期类型。

  • jmespath.Options 对象中提供一个您的子类实例。

以下是一些示例

import jmespath
from jmespath import functions

# 1. Create a subclass of functions.Functions.
#    The function.Functions base class has logic
#    that introspects all of its methods and automatically
#    registers your custom functions in its function table.
class CustomFunctions(functions.Functions):

    # 2 and 3.  Create a function that starts with _func_
    # and decorate it with @signature which indicates its
    # expected types.
    # In this example, we're creating a jmespath function
    # called "unique_letters" that accepts a single argument
    # with an expected type "string".
    @functions.signature({'types': ['string']})
    def _func_unique_letters(self, s):
        # Given a string s, return a sorted
        # string of unique letters: 'ccbbadd' ->  'abcd'
        return ''.join(sorted(set(s)))

    # Here's another example.  This is creating
    # a jmespath function called "my_add" that expects
    # two arguments, both of which should be of type number.
    @functions.signature({'types': ['number']}, {'types': ['number']})
    def _func_my_add(self, x, y):
        return x + y

# 4. Provide an instance of your subclass in a Options object.
options = jmespath.Options(custom_functions=CustomFunctions())

# Provide this value to jmespath.search:
# This will print 3
print(
    jmespath.search(
        'my_add(`1`, `2`)', {}, options=options)
)

# This will print "abcd"
print(
    jmespath.search(
        'foo.bar | unique_letters(@)',
        {'foo': {'bar': 'ccbbadd'}},
        options=options)
)

再次提醒,如果您开发出有用的函数,这些函数在JMESPath语言中(以及认为在所有JMESPath库中实施都有意义)非常有用,请通过jmespath.site告诉我们。

规范

如果您想了解更多关于JMESPath语言的信息,可以查看JMESPath教程。还可以查看JMESPath示例页面,了解更多复杂的jmespath查询示例。

语法使用ABNF指定,如RFC4234中所述。您可以在此处找到JMESPath的最新语法。

您可以在此处阅读JMESPath的完整规范。

测试

除了jmespath模块的单元测试外,还有一个包含测试用例的 tests/compliance 目录,这些测试用例以.json文件的形式存在。这允许其他实现验证它们是否生成正确的输出。每个json文件按功能分组。

讨论

如果您想聊天或有任何问题,请加入我们的Gitter频道

项目详情


下载文件

下载适用于您的平台的文件。如果您不确定选择哪个,请了解有关安装包的更多信息。

源分布

jmespath-1.0.1.tar.gz (25.8 kB 查看哈希值)

上传时间

构建分布

jmespath-1.0.1-py3-none-any.whl (20.3 kB 查看哈希值)

上传时间 Python 3

支持者

AWSAWS 云计算和安全赞助商 DatadogDatadog 监控 FastlyFastly CDN GoogleGoogle 下载分析 MicrosoftMicrosoft PSF赞助商 PingdomPingdom 监控 SentrySentry 错误日志 StatusPageStatusPage 状态页面