diff --git a/logbook-json/src/main/java/org/zalando/logbook/json/JsonPathBodyFilters.java b/logbook-json/src/main/java/org/zalando/logbook/json/JsonPathBodyFilters.java index 9a487201a..d4ceec862 100644 --- a/logbook-json/src/main/java/org/zalando/logbook/json/JsonPathBodyFilters.java +++ b/logbook-json/src/main/java/org/zalando/logbook/json/JsonPathBodyFilters.java @@ -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; @@ -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; @@ -58,6 +55,10 @@ public BodyFilter replace(final JsonNode replacement) { return filter(context -> context.set(path, replacement)); } + public BodyFilter replace(final UnaryOperator replacementFunction) { + return filter(context -> context.map(path, (node, config) -> new TextNode(replacementFunction.apply(node.toString())))); + } + public BodyFilter replace( final Pattern pattern, final String replacement) { diff --git a/logbook-json/src/test/java/org/zalando/logbook/json/JsonPathBodyFiltersTest.java b/logbook-json/src/test/java/org/zalando/logbook/json/JsonPathBodyFiltersTest.java index e61879caa..8e806eb4c 100644 --- a/logbook-json/src/test/java/org/zalando/logbook/json/JsonPathBodyFiltersTest.java +++ b/logbook-json/src/test/java/org/zalando/logbook/json/JsonPathBodyFiltersTest.java @@ -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");