JsonPath expression to filter using regex

拥有回忆 提交于 2019-12-22 04:24:24

问题


We are using a tool which uses jayway library for evaluating JSONpath expression. Javascript does NOT seem to work with it. How can I use regular expression in the JSONPath in such a case. For instance, in the below example I would like to filter all book titles whose title has the word "Sword" in it:

{
    "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
}

回答1:


The Jayway implementation uses the Ruby regex operator:

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

To ignore case:

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



回答2:


You could use capturing group or lookbehind assertion.

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

Add case-insensitive modifier i if necessary. Grab the title string from group index 1.

DEMO



来源:https://stackoverflow.com/questions/28954720/jsonpath-expression-to-filter-using-regex

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!