Issue
Problem: I have noticed that once [*] is in the path if the succeeding path key is present, it prints the value, but if the key is not present, it doesn't throw any exception.
JsonPath.read(json, "$.store.book[*].anyRandomKey")
should throw error when anyRandomKey is not present.
But it returns an empty list.
Below is code to replicate this scenario
pom.xml dependency:
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<version>2.4.0</version>
</dependency>
Java main class:
package main.java;
import com.jayway.jsonpath.JsonPath;
public class CheckValidPath {
public static void main(String[] args) {
String json = "{\n" +
" \"store\": {\n" +
" \"book\": [\n" +
" {\n" +
" \"category\": \"reference\",\n" +
" \"author\": \"Nigel Rees\",\n" +
" \"title\": \"Sayings of the Century\",\n" +
" \"price\": 8.95\n" +
" },\n" +
" {\n" +
" \"category\": \"fiction\",\n" +
" \"author\": \"Evelyn Waugh\",\n" +
" \"title\": \"Sword of Honour\",\n" +
" \"price\": 12.99\n" +
" },\n" +
" {\n" +
" \"category\": \"fiction\",\n" +
" \"author\": \"Herman Melville\",\n" +
" \"title\": \"Moby Dick\",\n" +
" \"isbn\": \"0-553-21311-3\",\n" +
" \"price\": 8.99\n" +
" },\n" +
" {\n" +
" \"category\": \"fiction\",\n" +
" \"author\": \"J. R. R. Tolkien\",\n" +
" \"title\": \"The Lord of the Rings\",\n" +
" \"isbn\": \"0-395-19395-8\",\n" +
" \"price\": 22.99\n" +
" }\n" +
" ],\n" +
" \"bicycle\": {\n" +
" \"color\": \"red\",\n" +
" \"price\": 19.95\n" +
" }\n" +
" },\n" +
" \"expensive\": 10\n" +
"}";
//Correct path is evaluated correctly
System.out.println(JsonPath.read(json, "$.store.book[*].author").toString());
//Wrong path doesn't throw a PathNotFoundException exception and returns an empty list
System.out.println(JsonPath.read(json, "$.store.book[*].anyRandomKey").toString());
}
}
Solution
Actually, it looks overcomplicated but it works as you need (throws PathNotFoundException for non existant path).
Just use this configuration:
Configuration configuration = Configuration.builder()
.options(Option.REQUIRE_PROPERTIES)
.build();
//Correct path is evaluated correctly
LOG.info(JsonPath.using(configuration)
.parse(json)
.read( "$.store.book[*].author").toString());
//Wrong path throws PathNotFoundException exception
LOG.info(JsonPath.using(configuration)
.parse(json)
.read("$.store.book[*].anyRandomKey").toString());
Answered By - Stargazer
Answer Checked By - Clifford M. (JavaFixing Volunteer)