Skip to content

Commit

Permalink
jsonpath support composite filter, for issue #2405
Browse files Browse the repository at this point in the history
  • Loading branch information
wenshao committed Apr 6, 2024
1 parent 86333ab commit 0dbfd58
Show file tree
Hide file tree
Showing 3 changed files with 67 additions and 4 deletions.
14 changes: 14 additions & 0 deletions core/src/main/java/com/alibaba/fastjson2/JSONPathFunction.java
Original file line number Diff line number Diff line change
Expand Up @@ -612,4 +612,18 @@ public Object apply(Object o) {
return null;
}
}

static final class FilterFunction
implements Function {
final JSONPathFilter filter;

FilterFunction(JSONPathFilter filter) {
this.filter = filter;
}

@Override
public Object apply(Object o) {
return null;
}
}
}
16 changes: 12 additions & 4 deletions core/src/main/java/com/alibaba/fastjson2/JSONPathParser.java
Original file line number Diff line number Diff line change
Expand Up @@ -709,14 +709,22 @@ JSONPathSegment parseFilter() {

if (function == null && jsonReader.ch == '[') {
jsonReader.next();
int index = jsonReader.readInt32Value();
function = new JSONPathFunction.IndexValue(index);
if (jsonReader.ch == '?') {
jsonReader.next();
JSONPathFilter subFilter = (JSONPathFilter) parseFilter();
function = new JSONPathFunction.FilterFunction(subFilter);
} else {
int index = jsonReader.readInt32Value();
function = new JSONPathFunction.IndexValue(index);
}
if (!jsonReader.nextIfMatch(']')) {
throw new JSONException("syntax error, [" + index);
throw new JSONException("syntax error");
}
}

if (operator == null) {
if (parentheses && jsonReader.nextIfMatch(')')) {
return new JSONPathFilter.NameExistsFilter(fieldName, hashCode);
}
operator = JSONPath.parseOperator(jsonReader);
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package com.alibaba.fastjson2.issues_2400;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONPath;
import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertEquals;

public class Issue2405 {
@Test
public void test() {
String path = "$.objects[?(@.objdata.Actions[?(@.Type == 'sun')])].objdata.PlantFoodActivationSound";
Object result = JSONPath.eval(STR, path);
assertEquals("[\"Play_Plant_TwinSunflower_Nitro\"]", JSON.toJSONString(result));
}

static final String STR = "{\n" +
" \"version\": 1,\n" +
" \"objects\": [\n" +
" {\n" +
" \"objclass\": \"SunflowerProps\",\n" +
" \"aliases\": [\n" +
" \"TwinSunflowerDefault\"\n" +
" ],\n" +
" \"objdata\": {\n" +
" \"PlantFoodActivationSound\": \"Play_Plant_TwinSunflower_Nitro\",\n" +
" \"CollectibleTypeName\": \"sun\",\n" +
" \"Actions\": [\n" +
" {\n" +
" \"Type\": \"sun\",\n" +
" \"SpawnOffset\": {\n" +
" \"x\": -10,\n" +
" \"y\": -55\n" +
" }\n" +
" }\n" +
" ]\n" +
" }\n" +
" }\n" +
" ]\n" +
"}";
}

0 comments on commit 0dbfd58

Please sign in to comment.