15

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
}
Casimir et Hippolyte
  • 88,009
  • 5
  • 94
  • 125
sjn
  • 171
  • 1
  • 1
  • 7

3 Answers3

16

The Jayway implementation uses the Ruby regex operator:

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

To ignore case:

$.store.book[?(@.title =~ /^.*sword.*$/i)]
kalle
  • 1,869
  • 14
  • 14
  • I tried the above expression with json-path-0.9.0 in the classpath (as the tool uses the version 0.9 internally) and the statement Object result = JsonPath.read(jsonStr, query); where jsonStr is the one shared in the example above. The result is an empty set – sjn Mar 10 '15 at 19:02
  • Regex support was added in 1.2.0. – kalle Mar 11 '15 at 19:58
  • Nice. If I want to get values of all keys that startswith title, How would I go about writing it? – karthikeyan Sep 10 '20 at 12:00
2

For the record, a workaround for conditional regex in Goessner's javascript JSONpath would be to write the query as follow:

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

Please see here https://github.com/jpaquit/jsonpath/tree/0.8.5-+-regexp for "=~" syntax in JS lib.

JPA
  • 21
  • 1
  • Any clues as to what `i.test` is? :D – bviktor Nov 08 '22 at 16:51
  • @bviktor "i" is the regex flag for "case-insensitive" and "test" is the dedicated JS function ;) https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test – JPA Nov 09 '22 at 22:39
0

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

Avinash Raj
  • 172,303
  • 28
  • 230
  • 274