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 @@ -133,8 +133,9 @@ private static Object readObjectProperty(String property, Object model, Evaluati

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;
// Normalize negative indices before creating PathRef so set/delete/map match read (#1077)
int effectiveIndex = index < 0 ? ctx.jsonProvider().length(model) + index : index;
PathRef pathRef = ctx.forUpdate() ? PathRef.create(model, effectiveIndex) : PathRef.NO_OP;
try {
Object evalHit = ctx.jsonProvider().getArrayIndex(model, effectiveIndex);
if (isLeaf()) {
Expand Down
26 changes: 26 additions & 0 deletions json-path/src/test/java/com/jayway/jsonpath/WriteTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,32 @@ public void an_array_index_can_be_updated() {
assertThat(res).isEqualTo("a");
}

@Test
public void a_negative_array_index_can_be_updated() {
// set/delete/map must resolve $[-1] like read (#1077)
DocumentContext ctx = parse("[\"a\",\"b\",\"c\"]");
assertThat(ctx.<String>read("$[-1]")).isEqualTo("c");

ctx.set("$[-1]", "z");
assertThat(ctx.<List<String>>json()).containsExactly("a", "b", "z");
assertThat(ctx.<String>read("$[-1]")).isEqualTo("z");
}

@Test
public void a_negative_array_index_can_be_deleted() {
DocumentContext ctx = parse("[\"a\",\"b\",\"c\"]");
ctx.delete("$[-1]");
assertThat(ctx.<List<String>>json()).containsExactly("a", "b");
}

@Test
public void a_negative_array_index_can_be_mapped() {
DocumentContext ctx = parse("[\"a\",\"b\",\"c\"]");
ctx.map("$[-1]", (currentValue, configuration) -> currentValue + "!");
assertThat(ctx.<List<String>>json()).containsExactly("a", "b", "c!");
assertThat(ctx.<String>read("$[-1]")).isEqualTo("c!");
}

@Test
public void an_array_slice_can_be_updated() {

Expand Down