Scrivio Interview library
CodingFoundations6 min read · updated 12 November 2026

Using Jayway JsonPath, write expressions for this document:

JSON
{"store":{"book":[{"title":"A","price":8},{"title":"B","price":12}]}}

Get all titles, titles of books cheaper than 10, and the number of books.

All titles are $.store.book[*].title, or $..title to find a title at any depth. The titles of books cheaper than 10 are $.store.book[?(@.price < 10)].title, and the number of books is $.store.book.length(). We run them with JsonPath.read(json, path), and because wildcards, deep scans and filters can match many nodes, they always return a List, even when only one book matches.

Why this question is asked

JsonPath is to JSON roughly what XPath is to XML: a short expression that picks values out of a document without writing loops. In Java, the Jayway JsonPath library is the common implementation, and Spring's MockMvc and its JSON test helpers use it under the hood, so we meet it in almost every Spring test suite. Interviewers ask a small exercise like this to check that we can write the basic expressions and that we know the one surprise that catches everyone, the List result. In this answer, we will recap the syntax, write each of the three expressions with its result, run them from Java, and then look at why filters return lists and how to read typed values.

1A Quick Recap of JsonPath Syntax

A JsonPath expression always starts at the root of the document, written $. From there we step down with a dot and a property name, so $.store means the store property of the root object. Square brackets select array elements: [0] is the first element, [*] means every element, and [0,1] or [0:2] pick several. Two dots, .., is the deep scan: it searches the current node and everything below it, at any depth, for the name that follows.

Inside brackets we can also write a filter, [?( ... )], which keeps only the elements for which the condition is true. In the condition, @ means the element currently being tested, so @.price is that book's price. Finally, Jayway adds functions that we append to the end of a path, such as length(), min(), max() and sum().

Here is the document from the question, which we will query throughout.

JSON
{
"store": {
"book": [
{ "title": "A", "price": 8 },
{ "title": "B", "price": 12 }
]
}
}

2Writing the Three Expressions

For all titles, we go to the book array, take every element with [*], and take its title. The deep scan version finds every property called title anywhere in the document, which gives the same answer here but would also pick up, say, a magazine's title if the store had magazines. So the explicit path is safer when we know the structure.

For cheap books, we put a filter on the array and then take the title of each element that passed. For the count, we apply the length() function to the array.

Text
$.store.book[*].title // ["A","B"]
$..title // ["A","B"] (any depth)
$.store.book[?(@.price < 10)].title // ["A"]
$.store.book.length() // 2
$.store.book[0].title // "A" (one definite value, not a list)
Which expressions return a list
ExpressionDefinite?Result type
$.store.book[0].titleyesString: "A"
$.store.book[*].titleno, wildcardList: ["A","B"]
$..titleno, deep scanList: ["A","B"]
$.store.book[?(@.price < 10)].titleno, filterList: ["A"]
$.store.book.length()function on one arrayInteger: 2

Notice the last line, which we added for contrast. A path made only of property names and single indexes is called definite: it can point to at most one value, so the result is that value. Any path with [*], .. or a filter is indefinite: it can match many nodes, so the result is a list.

3Running Them From Java

With Jayway JsonPath on the classpath (com.jayway.jsonpath:json-path), the static JsonPath.read() method parses the document and evaluates one path. If we need several paths on the same document, we parse it once with JsonPath.parse() and read from the resulting DocumentContext, which avoids parsing the text again for each query.

Java
import com.jayway.jsonpath.*;
import static com.jayway.jsonpath.Criteria.where;
import static com.jayway.jsonpath.Filter.filter;
String json = "{\"store\":{\"book\":[{\"title\":\"A\",\"price\":8},{\"title\":\"B\",\"price\":12}]}}";
List<String> titles = JsonPath.read(json, "$.store.book[*].title");
System.out.println(titles); // [A, B]
DocumentContext doc = JsonPath.parse(json); // parse once, query many times
List<String> cheap = doc.read("$.store.book[?(@.price < 10)].title");
System.out.println(cheap); // [A]
int count = doc.read("$.store.book.length()");
System.out.println(count); // 2
// The same filter, built in Java instead of in the string
Filter under10 = filter(where("price").lt(10));
List<String> cheap2 = doc.read("$.store.book[?].title", under10);
System.out.println(cheap2); // [A]

The result types are inferred from the variable we assign to, so reading a list into a String variable would fail with a ClassCastException at runtime. The Filter API in the last block does the same job as the inline filter, and it is handy when the threshold comes from a variable, because we do not have to build the expression string by hand.

4Why a Filter Returns a List Even for One Match

This is the classic surprise. Only one book costs less than 10, so it is natural to expect the string "A". But JsonPath decides the result type from the expression, not from the data. A filter could match zero, one or a hundred books, so the result is always a list, and a list with one element is still a list.

So code such as String t = JsonPath.read(json, "$.store.book[?(@.price < 10)].title") compiles, because read() is generic, and then fails at runtime with a ClassCastException. The fix is to read a List and take the first element when we really expect exactly one, and to check the size first, so a second cheap book in tomorrow's data does not go unnoticed.

Java
List<String> found = JsonPath.read(json, "$.store.book[?(@.price < 10)].title");
if (found.size() != 1) throw new IllegalStateException("expected one cheap book, got " + found);
String title = found.get(0); // A

5Reading Typed Values

Numbers deserve a word. With the default JSON provider, an integer such as 8 comes back as an Integer and 8.5 as a Double. When we want our own types, we configure a mapping provider, for example Jackson, and read with a TypeRef, which carries the generic type at runtime.

Java
Configuration conf = Configuration.builder()
.jsonProvider(new JacksonJsonProvider())
.mappingProvider(new JacksonMappingProvider())
.build();
record Book(String title, int price) {}
List<Book> books = JsonPath.using(conf).parse(json)
.read("$.store.book[*]", new TypeRef<List<Book>>() {});
System.out.println(books.get(1).price()); // 12

6Follow-up questions

Is $..title always the same as $.store.book[*].title?

Only in this document. The deep scan finds every title property at any depth, so if the store also had a magazine array or a book had a nested series object with its own title, $..title would return those too. It is also slower on large documents because it visits every node. Use it when we really do not know the depth.

How do you combine conditions in a filter?

With && and || inside the filter, for example $.store.book[?(@.price < 10 && @.title == 'A')].title. Jayway also supports operators like in, nin, size, empty and the regular expression operator =~, but these are Jayway extensions, not part of the standard JSONPath in RFC 9535, so they may not work in other engines.

What happens if the path does not exist?

With the default configuration, a definite path that does not exist throws PathNotFoundException, while an indefinite path simply returns an empty list. Options such as SUPPRESS_EXCEPTIONS and DEFAULT_PATH_LEAF_TO_NULL change this, which is convenient but can hide mistakes in tests.

7Conclusion

In this answer, we wrote $.store.book[*].title and $..title for all titles, $.store.book[?(@.price < 10)].title for the cheap ones and $.store.book.length() for the count. We ran them with JsonPath.read and with a DocumentContext parsed once, built the same filter with the Filter API, and saw that wildcards, deep scans and filters always produce a List, even with a single match, while definite paths return a single value.

What to say in the interviewAbout 100 seconds aloud

Open with

For all the titles I would write dollar, store, book, star, title, which goes to the book array, takes every element and reads its title, giving A and B.

Then, if they want more

If I did not know how deep the titles were, I could use the deep scan, dollar dot dot title, which finds a title property at any depth, but it would also pick up titles from other parts of the document, so I prefer the explicit path when I know the structure.

For books cheaper than 10, I put a filter on the array: book, then question mark with the condition at-sign dot price less than 10 in brackets, then dot title. The at-sign means the element being tested, and the result is a list containing A. For the count I use Jayway's length function on the array, which returns 2.

In Java I would call JsonPath.read with the document and the path, or parse once with JsonPath.parse and read several paths from the DocumentContext. The thing I would point out is the result type. Any path with a wildcard, a deep scan or a filter is indefinite, so JsonPath returns a List even when exactly one book matches.

If I assign that to a String, it compiles but throws a ClassCastException at runtime, so I read a List, check its size and take the element. Only definite paths, like book index zero dot title, return a single value.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Using Jayway JsonPath, write expressions for this document:": https://scrivio-interview-library.netlify.app/java/json-libraries/3741711d40/