跳转到主要内容

JSON匹配表达式

项目描述

JMESPath

JMESPath(发音为“jaymz 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”]。

注意:jmespath正在积极开发。它目前不支持的一些功能可能会在未来添加。

语法

语法使用ABNF指定,如RFC4234中所述

expression        = sub-expression / index-expression / or-expression / identifier / "*"
sub-expression    = expression "." expression
or-expression     = expression "||" expression
index-expression  = expression bracket-specifier / bracket-specifier
bracket-specifier = "[" (number / "*") "]"
number            = [-]1*digit
digit             = "1" / "2" / "3" / "4" / "5" / "6" / "7" / "8" / "9" / "0"
identifier        = 1*char
char              = unescaped /
                    escape (
                        %x20-2F /    ; Space,!,",#,$,%,&,',(,),*,+,comma,-,.,/
                        %x3A-40 /    ; :,;,<,=,>,?,@
                        %x5B    /    ; Left bracket: [
                        %x5C    /    ; Back slash: \
                        %x5D    /    ; Right bracket: ]
                        %x5E    /    ; Caret: ^
                        %x60    /    ; Backtick: `
                        %x7B-7E /    ; {,|,},~
                        b       /    ; backspace
                        n       /    ; new line
                        f       /    ; form feed
                        r       /    ; carriage return
                        t       )    ; tab
escape            = %x5C   ; Back slash: \
unescaped         = %x30-39 / %x41-5A / %x5F / %x61-7A / %x7F-10FFFF

测试

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

Python库

包含的Python实现有两个操作在Python数据结构上的便利函数。您可以使用 search 并给它jmespath表达式和数据

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

类似于 re 模块,您可以将编译的表达式存储并重复使用以执行重复搜索

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

如果需要更多控制,您还可以直接使用 jmespath.parser.Parser 类。

项目详情


支持

AWS AWS 云计算和安全赞助商 Datadog Datadog 监控 Fastly Fastly CDN Google Google 下载分析 Microsoft Microsoft PSF赞助商 Pingdom Pingdom 监控 Sentry Sentry 错误日志 StatusPage StatusPage 状态页面