Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JsonPath dynamic value replacing implementation and testing ( resolves #1127 ) #1128

Merged
merged 3 commits into from
Aug 27, 2021
Merged
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 @@ -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