简体   繁体   English

使用正则表达式过滤的 JsonPath 表达式

[英]JsonPath expression to filter using regex

We are using a tool which uses jayway library for evaluating JSONpath expression.我们正在使用一个工具,它使用 jayway 库来评估 JSONpath 表达式。 Javascript does NOT seem to work with it . Javascript 似乎不适用于它 How can I use regular expression in the JSONPath in such a case.在这种情况下,如何在 JSONPath 中使用正则表达式。 For instance, in the below example I would like to filter all book titles whose title has the word "Sword" in it:例如,在下面的示例中,我想过滤标题中包含“Sword”一词的所有书名:

{
    "store": {
        "book": [
            {
                "category": "reference",
                "author": "Nigel Rees",
                "title": "Sayings of the Century",
                "price": 8.95
            },
            {
                "category": "fiction",
                "author": "Evelyn Waugh",
                "title": "Sword of Honour",
                "price": 12.99
            },
            {
                "category": "fiction",
                "author": "Herman Melville",
                "title": "Moby Dick",
                "isbn": "0-553-21311-3",
                "price": 8.99
            },
            {
                "category": "fiction",
                "author": "J. R. R. Tolkien",
                "title": "The Lord of the Rings",
                "isbn": "0-395-19395-8",
                "price": 22.99
            }
        ],
        "bicycle": {
            "color": "red",
            "price": 19.95
        }
    },
    "expensive": 10
}

The Jayway implementation uses the Ruby regex operator: Jayway 实现使用 Ruby 正则表达式运算符:

$.store.book[?(@.title =~ /^.*Sword.*$/)]

To ignore case:忽略大小写:

$.store.book[?(@.title =~ /^.*sword.*$/i)]

You could use capturing group or lookbehind assertion.您可以使用捕获组或后视断言。

"title":\s*"([^"]*\bSword\b[^"]*)"

Add case-insensitive modifier i if necessary.如有必要,添加不区分大小写的修饰符i Grab the title string from group index 1.从组索引 1 中获取标题字符串。

DEMO演示

For the record, a workaround for conditional regex in Goessner's javascript JSONpath would be to write the query as follow:作为记录,Goessner 的 javascript JSONpath 中条件正则表达式的解决方法是编写如下查询:

$.store.book[?(/^.*sword.*$/i.test(@.title))]

Please see here https://github.com/jpaquit/jsonpath/tree/0.8.5-+-regexp for "=~" syntax in JS lib.请在此处查看https://github.com/jpaquit/jsonpath/tree/0.8.5-+-regexp以了解 JS 库中的“=~”语法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM