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

Introduce random JsonPath function #4

Merged
merged 1 commit into from
Mar 1, 2024
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
32 changes: 17 additions & 15 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,21 +58,23 @@ Functions
Functions can be invoked at the tail end of a path - the input to a function is the output of the path expression.
The function output is dictated by the function itself.

| Function | Description | Output type |
|:------------|:-------------------------------------------------------------------------------------|:---------------------|
| `min()` | Provides the min value of an array of numbers | Double |
| `max()` | Provides the max value of an array of numbers | Double |
| `avg()` | Provides the average value of an array of numbers | Double |
| `stddev()` | Provides the standard deviation value of an array of numbers | Double |
| `length()` | Provides the length of an array | Integer |
| `sum()` | Provides the sum value of an array of numbers | Double |
| `keys()` | Provides the property keys (An alternative for terminal tilde `~`) | `Set<E>` |
| `concat(X)` | Provides a concatinated version of the path output with a new item | like input |
| `append(X)` | add an item to the json path output array | like input |
| `first()` | Provides the first item of an array | Depends on the array |
| `last()` | Provides the last item of an array | Depends on the array |
| `index(X)` | Provides the item of an array of index: X, if the X is negative, take from backwards | Depends on the array |
| `distinct()`| Provides an array containing only unique items from the input array | List<E> |
| Function | Description | Output type |
|:------------|:---------------------------------------------------------------------------------------|:---------------------|
| `min()` | Provides the min value of an array of numbers | Double |
| `max()` | Provides the max value of an array of numbers | Double |
| `avg()` | Provides the average value of an array of numbers | Double |
| `stddev()` | Provides the standard deviation value of an array of numbers | Double |
| `length()` | Provides the length of an array | Integer |
| `sum()` | Provides the sum value of an array of numbers | Double |
| `keys()` | Provides the property keys (An alternative for terminal tilde `~`) | `Set<E>` |
| `concat(X)` | Provides a concatinated version of the path output with a new item | like input |
| `append(X)` | add an item to the json path output array | like input |
| `first()` | Provides the first item of an array | Depends on the array |
| `last()` | Provides the last item of an array | Depends on the array |
| `index(X)` | Provides the item of an array of index: X, if the X is negative, take from backwards | Depends on the array |
| `distinct()`| Provides an array containing only unique items from the input array | List<E> |
| `random()` | Provides one random item from the array | Depends on the array |

Filter Operators
-----------------

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
import com.jayway.jsonpath.internal.function.sequence.First;
import com.jayway.jsonpath.internal.function.sequence.Index;
import com.jayway.jsonpath.internal.function.sequence.Last;
import com.jayway.jsonpath.internal.function.sequence.Random;
import com.jayway.jsonpath.internal.function.text.Concatenate;
import com.jayway.jsonpath.internal.function.text.Length;

Expand Down Expand Up @@ -56,6 +57,7 @@ public class PathFunctionFactory {
map.put("last", Last.class);
map.put("distinct", Distinct.class);
map.put("index", Index.class);
map.put("random", Random.class);


FUNCTIONS = Collections.unmodifiableMap(map);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package com.jayway.jsonpath.internal.function.sequence;

import com.jayway.jsonpath.JsonPathException;
import com.jayway.jsonpath.internal.EvaluationContext;
import com.jayway.jsonpath.internal.PathRef;
import com.jayway.jsonpath.internal.function.Parameter;
import com.jayway.jsonpath.internal.function.PathFunction;

import java.security.SecureRandom;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;

/**
* Take a random item from collection of JSONArray
*/
public class Random implements PathFunction {
@Override
public Object invoke(String currentPath, PathRef parent, Object model, EvaluationContext ctx, List<Parameter> parameters) {
if (ctx.configuration().jsonProvider().isArray(model)) {
Iterable<?> objects = ctx.configuration().jsonProvider().toIterable(model);
List<?> elements = StreamSupport.stream(objects.spliterator(), false)
.collect(Collectors.toList());

if (elements.isEmpty()) {
throw new JsonPathException("Aggregation function attempted to get a random item from empty array");
}

SecureRandom rand = new SecureRandom();
return elements.get(rand.nextInt(elements.size()));
}
throw new JsonPathException("Aggregation function attempted to get a random item from not array");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,12 @@ public class BaseFunctionTest {
* The expected value to be returned from the test
*/
protected void verifyFunction(Configuration conf, String pathExpr, String json, Object expectedValue) {
assertThat(evaluate(conf, pathExpr, json)).isEqualTo(expectedValue);
}

protected Object evaluate(Configuration conf, String pathExpr, String json) {
Object result = using(conf).parse(json).read(pathExpr);
assertThat(conf.jsonProvider().unwrap(result)).isEqualTo(expectedValue);
return conf.jsonProvider().unwrap(result);
}

protected void verifyMathFunction(Configuration conf, String pathExpr, Object expectedValue) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
package com.jayway.jsonpath.internal.function;

import static com.jayway.jsonpath.JsonPath.using;
import static org.assertj.core.api.Assertions.assertThat;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.jayway.jsonpath.Configuration;
import com.jayway.jsonpath.Configurations;
import java.util.Arrays;
import java.util.List;

import com.jayway.jsonpath.spi.json.JacksonJsonProvider;
import com.jayway.jsonpath.spi.mapper.JacksonMappingProvider;
Expand All @@ -18,6 +20,7 @@
* -last
* -index(X)
* -distinct
* -random
*
* Created by git9527 on 6/11/22.
*/
Expand Down Expand Up @@ -90,4 +93,18 @@ public void testDistinctOfEmptyObjects() throws Exception {
final Object expectedValue = Configuration.defaultConfiguration().jsonProvider().parse("[]");
verifyFunction(conf, "$.empty.distinct()", OBJECT_SERIES, expectedValue);
}

@Test
public void testRandomForStrings() throws Exception {
List<Object> elements = (List<Object>) evaluate(conf, "$.text", TEXT_AND_NUMBER_SERIES);
Object randomElement = evaluate(conf, "$.text.random()", TEXT_AND_NUMBER_SERIES);
assertThat(randomElement).isInstanceOf(String.class).isIn(elements);
}

@Test
public void testRandomForNumbers() throws Exception {
List<Object> elements = (List<Object>) evaluate(conf, "$.numbers", TEXT_AND_NUMBER_SERIES);
Object randomElement = evaluate(conf, "$.numbers.random()", TEXT_AND_NUMBER_SERIES);
assertThat(randomElement).isInstanceOf(Integer.class).isIn(elements);
}
}
Loading