Skip to content

Commit

Permalink
improved jsonpath, for issue #2401
Browse files Browse the repository at this point in the history
  • Loading branch information
wenshao committed Apr 6, 2024
1 parent c7aa978 commit 7493a2f
Show file tree
Hide file tree
Showing 3 changed files with 71 additions and 0 deletions.
29 changes: 29 additions & 0 deletions core/src/main/java/com/alibaba/fastjson2/JSONPathFunction.java
Original file line number Diff line number Diff line change
Expand Up @@ -583,4 +583,33 @@ protected boolean eq(Object item) {
return value.equals(item.toString());
}
}

static final class IndexValue
implements Function {
final int index;

public IndexValue(int index) {
this.index = index;
}

@Override
public Object apply(Object o) {
if (o == null) {
return null;
}

if (o instanceof List) {
return ((List) o).get(index);
}

if (o.getClass().isArray()) {
int len = Array.getLength(o);
for (int i = 0; i < len; i++) {
return Array.get(o, i);
}
}

return null;
}
}
}
9 changes: 9 additions & 0 deletions core/src/main/java/com/alibaba/fastjson2/JSONPathParser.java
Original file line number Diff line number Diff line change
Expand Up @@ -707,6 +707,15 @@ JSONPathSegment parseFilter() {
}
}

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

if (operator == null) {
operator = JSONPath.parseOperator(jsonReader);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
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 Issue2401 {
@Test
public void test() {
String str = "{\n" +
"\t\"objects\": [\n" +
"\t\t{\n" +
"\t\t\t\"objclass\": \"GamePropertySheet\",\n" +
"\t\t\t\"aliases\": [\n" +
"\t\t\t\t\"DefaultGameProps\"\n" +
"\t\t\t],\n" +
"\t\t\t\"objdata\": {\n" +
"\t\t\t\t\"Plants\": [\n" +
"\t\t\t\t\t\"plant1\",\n" +
"\t\t\t\t\t\"plant2\"\n" +
"\t\t\t\t]\n" +
"\t\t\t}\n" +
"\t\t}\n" +
"\t]\n" +
"}";

String path = "$.objects[?(@.aliases[0] == 'DefaultGameProps')].objdata";
Object result = JSONPath.eval(str, path);
assertEquals("[{\"Plants\":[\"plant1\",\"plant2\"]}]", JSON.toJSONString(result));
}
}

0 comments on commit 7493a2f

Please sign in to comment.