Skip to content

Commit

Permalink
JsonPath dynamic value replacing implementation and testing. Resolves z…
Browse files Browse the repository at this point in the history
  • Loading branch information
atrujillofalcon committed Aug 26, 2021
1 parent dfa3d05 commit a941085
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,7 @@
import com.fasterxml.jackson.databind.node.BooleanNode;
import com.fasterxml.jackson.databind.node.DoubleNode;
import com.fasterxml.jackson.databind.node.TextNode;
import com.jayway.jsonpath.Configuration;
import com.jayway.jsonpath.DocumentContext;
import com.jayway.jsonpath.JsonPath;
import com.jayway.jsonpath.Option;
import com.jayway.jsonpath.ParseContext;
import com.jayway.jsonpath.*;
import com.jayway.jsonpath.spi.json.JacksonJsonNodeJsonProvider;
import com.jayway.jsonpath.spi.mapper.JacksonMappingProvider;

Expand All @@ -21,6 +17,7 @@
import javax.annotation.Nullable;
import java.util.Arrays;
import java.util.Collection;
import java.util.function.UnaryOperator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

Expand Down Expand Up @@ -58,6 +55,10 @@ public BodyFilter replace(final JsonNode replacement) {
return filter(context -> context.set(path, replacement));
}

public BodyFilter replace(final UnaryOperator<String> replacementFunction) {
return filter(context -> context.map(path, (node, config) -> new TextNode(replacementFunction.apply(node.toString()))));
}

public BodyFilter replace(
final Pattern pattern, final String replacement) {

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,23 @@ void replacesObjectDynamically() {
.assertEquals("grades.PE", "XXX");
}

@Test
void replacesValuesDynamically() {
final BodyFilter unit = jsonPath("$.name").replace(String::toUpperCase);

with(unit.filter(type, student))
.assertEquals("name", "ALICE");
}

@Test
void replacesArrayValuesDynamically() {
final BodyFilter unit = jsonPath("$.friends.*.name").replace(String::toUpperCase);

with(unit.filter(type, student))
.assertEquals("friends[0].name", "BOB")
.assertEquals("friends[1].name", "CHARLIE");
}

@Test
void fallsBackTorReplaceObjectAsString() {
final BodyFilter unit = jsonPath("$.grades").replace(compile("(\\d+)\\.\\d+"), "$1.X");
Expand Down

0 comments on commit a941085

Please sign in to comment.