Search code examples
javapythonjsonjsonpath

Getting Could not compile inline filter : <Jsonpath with Query>


I was trying to get json array using query with json path I used following maven repo

I used com.jayway.jsonpath version 2.4.0 from maven

Json Is :

{
    "verdict": [
        {
            "firstSeenOn": "2015-01-21T07:56:00.000+0000",
            "lastSeenOn": "2019-05-14T14:35:00.000+0000",
            "reputationStatus": "KNOWN",
            "scannerCount": 43,
            "scannerPercentage": 2,
            "threatLevel": 0,
            "trustFactor": 2,
            "sha256": "b80ff3bb189960738bc94973c7bc25e541c1bdff5b9c1c69973a13345ffbc3c3"
        },
        {
            "reputationStatus": "UNKNOWN",
            "scannerCount": 0,
            "scannerPercentage": 0,
            "threatLevel": 0,
            "trustFactor": 0,
            "sha256": "06a4feb0ff348dc5a8951b7f20e5dbf30d733ff2ecf6f204fd55fb8348c99e85"
        }


    ]

}

I used json path :

$.verdict.[?(@.["reputationStatus"]=="KNOWN")].sha256

and the error is

com.jayway.jsonpath.InvalidPathException: Could not compile inline filter : [?(@.["reputationStatus"]=="KNOWN")]
    at com.jayway.jsonpath.internal.filter.FilterCompiler.compile(FilterCompiler.java:47)
    at com.jayway.jsonpath.internal.path.PathCompiler.readFilterToken(PathCompiler.java:255)
    at com.jayway.jsonpath.internal.path.PathCompiler.readNextToken(PathCompiler.java:107)




    ... 34 common frames omitted
Caused by: com.jayway.jsonpath.InvalidPathException: Could not parse token starting at position 2. Expected ?, ', 0-9, * 
    at com.jayway.jsonpath.internal.path.PathCompiler.fail(PathCompiler.java:387)
    at com.jayway.jsonpath.internal.path.PathCompiler.readNextToken(PathCompiler.java:109)




Solution

  • Correct Json Path is

    $.verdict[?(@.reputationStatus=="KNOWN")].sha256

    which returns

    [
      "b80ff3bb189960738bc94973c7bc25e541c1bdff5b9c1c69973a13345ffbc3c3"
    ]
    

    EDIT: I tried using jsonpath library and both the json path expressions give correct output.

    import com.jayway.jsonpath.JsonPath;
    
    import net.minidev.json.JSONArray;
    
    public class JsonPathExample {
    
        private static final String json = "JSON STRING";
    
        public static void main(String[] args) {
            JSONArray output = JsonPath.read(json, "$.verdict[?(@.reputationStatus==\"KNOWN\")].sha256");
            System.out.println(output.toJSONString());
            JSONArray output2 = JsonPath.read(json, "$.verdict.[?(@.[\"reputationStatus\"]==\"KNOWN\")].sha256");
            System.out.println(output2.toJSONString());
        }
    
    }