fix issue with NestedPathArrayElement not correctly handling negative index for Object[] like it has for List (#15650)

This commit is contained in:
Clint Wylie 2024-01-09 20:16:08 -08:00 committed by GitHub
parent 71f5307277
commit 2938b8de53
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 24 additions and 4 deletions

View File

@ -46,15 +46,21 @@ public class NestedPathArrayElement implements NestedPathPart
List<?> currentList = (List<?>) input;
final int currentSize = currentList.size();
if (index < 0) {
if (currentSize + index >= 0) {
return currentList.get(currentSize + index);
final int adjusted = currentSize + index;
if (adjusted >= 0) {
return currentList.get(adjusted);
}
} else if (currentList.size() > index) {
return currentList.get(index);
}
} else if (input instanceof Object[]) {
Object[] currentList = (Object[]) input;
if (currentList.length > index) {
if (index < 0) {
final int adjusted = currentList.length + index;
if (adjusted >= 0) {
return currentList[adjusted];
}
} else if (currentList.length > index) {
return currentList[index];
}
}

View File

@ -36,7 +36,8 @@ public class NestedPathFinderTest
"y", ImmutableMap.of("a", "hello", "b", "world"),
"z", "foo",
"[sneaky]", "bar",
"[also_sneaky]", ImmutableList.of(ImmutableMap.of("a", "x"), ImmutableMap.of("b", "y", "c", "z"))
"[also_sneaky]", ImmutableList.of(ImmutableMap.of("a", "x"), ImmutableMap.of("b", "y", "c", "z")),
"objarray", new Object[]{"a", "b", "c"}
);
@Test
@ -436,6 +437,19 @@ public class NestedPathFinderTest
pathParts = NestedPathFinder.parseJqPath(".x[-4]");
Assert.assertNull(NestedPathFinder.find(NESTER, pathParts));
// object array
pathParts = NestedPathFinder.parseJqPath(".objarray[1]");
Assert.assertEquals("b", NestedPathFinder.find(NESTER, pathParts));
pathParts = NestedPathFinder.parseJqPath(".objarray[-1]");
Assert.assertEquals("c", NestedPathFinder.find(NESTER, pathParts));
pathParts = NestedPathFinder.parseJqPath(".objarray[-2]");
Assert.assertEquals("b", NestedPathFinder.find(NESTER, pathParts));
pathParts = NestedPathFinder.parseJqPath(".objarray[-4]");
Assert.assertNull(NestedPathFinder.find(NESTER, pathParts));
// nonexistent
pathParts = NestedPathFinder.parseJqPath(".x[1].y.z");
Assert.assertNull(NestedPathFinder.find(NESTER, pathParts));