Browse Source

support negative array indexes

pull/329/head
Jochen Berger 7 years ago
parent
commit
43414d8457
  1. 2
      json-path/src/main/java/com/jayway/jsonpath/internal/path/ArrayIndexOperation.java
  2. 3
      json-path/src/main/java/com/jayway/jsonpath/internal/path/PathToken.java
  3. 9
      json-path/src/test/java/com/jayway/jsonpath/old/internal/ArrayIndexFilterTest.java

2
json-path/src/main/java/com/jayway/jsonpath/internal/path/ArrayIndexOperation.java

@ -42,7 +42,7 @@ public class ArrayIndexOperation {
//check valid chars
for (int i = 0; i < operation.length(); i++) {
char c = operation.charAt(i);
if (!isDigit(c) && c != ',' && c != ' ') {
if (!isDigit(c) && c != ',' && c != ' ' && c != '-') {
throw new InvalidPathException("Failed to parse ArrayIndexOperation: " + operation);
}
}

3
json-path/src/main/java/com/jayway/jsonpath/internal/path/PathToken.java

@ -125,8 +125,9 @@ public abstract class PathToken {
protected void handleArrayIndex(int index, String currentPath, Object model, EvaluationContextImpl ctx) {
String evalPath = Utils.concat(currentPath, "[", String.valueOf(index), "]");
PathRef pathRef = ctx.forUpdate() ? PathRef.create(model, index) : PathRef.NO_OP;
int effectiveIndex = index < 0 ? ctx.jsonProvider().length(model) + index : index;
try {
Object evalHit = ctx.jsonProvider().getArrayIndex(model, index);
Object evalHit = ctx.jsonProvider().getArrayIndex(model, effectiveIndex);
if (isLeaf()) {
ctx.addResult(evalPath, pathRef, evalHit);
} else {

9
json-path/src/test/java/com/jayway/jsonpath/old/internal/ArrayIndexFilterTest.java

@ -1,6 +1,9 @@
package com.jayway.jsonpath.old.internal;
import com.jayway.jsonpath.JsonPath;
import org.junit.Assert;
import org.hamcrest.Matchers;
import org.junit.Test;
@ -43,4 +46,10 @@ public class ArrayIndexFilterTest {
assertThat(result, Matchers.contains(1, 3, 5));
}
@Test
public void can_access_items_from_end_with_negative_index() {
int result = JsonPath.parse(JSON).read("$[-3]");
Assert.assertEquals(8, result);
}
}

Loading…
Cancel
Save