Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -678,7 +678,14 @@ public ValueNode evaluate(Predicate.PredicateContext ctx) {
try {
Configuration c = Configuration.builder().jsonProvider(ctx.configuration().jsonProvider()).options(Option.REQUIRE_PROPERTIES).build();
Object result = path.evaluate(ctx.item(), ctx.root(), c).getValue(false);
return result == JsonProvider.UNDEFINED ? FALSE : TRUE;
if (result == JsonProvider.UNDEFINED) {
return FALSE;
}
// If the result is an empty array, return FALSE for exists checks
if (ctx.configuration().jsonProvider().isArray(result) && ctx.configuration().jsonProvider().length(result) == 0) {
return FALSE;
}
return TRUE;
} catch (PathNotFoundException e) {
return FALSE;
}
Expand Down
26 changes: 26 additions & 0 deletions json-path/src/test/java/com/jayway/jsonpath/ExistsCheckTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package com.jayway.jsonpath;

import org.junit.jupiter.api.Test;

import java.util.List;

import static org.assertj.core.api.Assertions.assertThat;

public class ExistsCheckTest extends BaseTest {

@Test
public void deep_products_exists_returns_only_store_b() {
String json = "[" +
"{\"id\":1,\"name\":\"Store A\",\"departments\":[{\"id\":10,\"name\":\"Electronics\",\"products\":[{\"id\":101,\"name\":\"TV\",\"in_stock\":true},{\"id\":102,\"name\":\"Laptop\",\"in_stock\":false}]},{\"id\":11,\"name\":\"Clothing\",\"products\":[{\"id\":201,\"name\":\"Shirt\",\"in_stock\":true},{\"id\":202,\"name\":\"Jeans\",\"in_stock\":true}]}]} ," +
"{\"id\":2,\"name\":\"Store B\",\"departments\":[{\"id\":12,\"name\":\"Grocery\",\"products\":[{\"id\":301,\"name\":\"Milk\",\"in_stock\":false},{\"id\":302,\"name\":\"Eggs\",\"in_stock\":true}]}]}" +
"]";

Object doc = Configuration.defaultConfiguration().jsonProvider().parse(json);

List<String> res1 = JsonPath.read(doc, "$[?(@..products[?(@.id==302)])].name");
assertThat(res1).containsExactly("Store B");

List<String> res2 = JsonPath.read(doc, "$[?(@.departments[?(@.products[?(@.id==302)])])].name");
assertThat(res2).containsExactly("Store B");
}
}