Skip to content

Commit

Permalink
Merge pull request #440 from sergey-sw/master
Browse files Browse the repository at this point in the history
Add keys function for Map objects
  • Loading branch information
kallestenflo authored Dec 10, 2020
2 parents ba35cf9 + 7355e30 commit 1e18a13
Show file tree
Hide file tree
Showing 4 changed files with 55 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import com.jayway.jsonpath.InvalidPathException;
import com.jayway.jsonpath.internal.function.json.Append;
import com.jayway.jsonpath.internal.function.json.KeySetFunction;
import com.jayway.jsonpath.internal.function.numeric.Average;
import com.jayway.jsonpath.internal.function.numeric.Max;
import com.jayway.jsonpath.internal.function.numeric.Min;
Expand Down Expand Up @@ -44,6 +45,7 @@ public class PathFunctionFactory {
map.put("length", Length.class);
map.put("size", Length.class);
map.put("append", Append.class);
map.put("keys", KeySetFunction.class);


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

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.util.List;

/**
* Author: Sergey Saiyan [email protected]
* Created at 21/02/2018.
*/
public class KeySetFunction implements PathFunction {

@Override
public Object invoke(String currentPath, PathRef parent, Object model, EvaluationContext ctx, List<Parameter> parameters) {
if (ctx.configuration().jsonProvider().isMap(model)) {
return ctx.configuration().jsonProvider().getPropertyKeys(model);
}
return null;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package com.jayway.jsonpath.internal.function;

import com.jayway.jsonpath.Configuration;
import com.jayway.jsonpath.Configurations;
import org.apache.commons.io.IOUtils;
import org.junit.Test;

import java.util.Arrays;
import java.util.HashSet;

/**
* Author: Sergey Saiyan [email protected]
* Created at 21/02/2018.
*/
public class KeySetFunctionTest extends BaseFunctionTest {

private Configuration conf = Configurations.JACKSON_CONFIGURATION;

@Test
public void testKeySet() throws Exception {
String json = IOUtils.toString(getClass().getResourceAsStream("/keyset.json"));
verifyFunction(conf, "$.data.keys()", json, new HashSet<String>(Arrays.asList("a", "b")));
}
}
6 changes: 6 additions & 0 deletions json-path/src/test/resources/keyset.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"data" : {
"a" : "a",
"b" : "b"
}
}

0 comments on commit 1e18a13

Please sign in to comment.