Search code examples
javajsonpath

Using Jaca JsonPath to exclude items from JSON response


I am using the JsonSmartJsonProvider and my JSON looks like this

  {
  "info": {
    "clientCount": 1,
    "compactorVersion": 2,
    "processMonitor": {
      "processList": [
        {
          "name": "java.exe",
          "commandLine": "",
          "pid": 6224
        }
      ]
    }
  }
}

I'm trying to exclude "processList", but keep everything else. I've tried variations on $.info[?(@ noneof ['processMonitor'])], but I always end up with "info" being empty in the response. Is it possible to use JsonPath to do this? The code that is used to do this looks like this:

        DocumentContext document = JsonPath.using(CONFIGURATION).parse(json);
        
        Map<String, Object> result = new HashMap<>();
        paths.forEach((key, value) -> result.put(key, document.read(value)));
        return result;

Solution

  • As mentioned, you are actually looking for a JSON transformation. JOLT is a common library to do just that. A solution can look like this:

    import java.util.List;
    import com.bazaarvoice.jolt.Chainr;
    import com.bazaarvoice.jolt.JsonUtils;
     
    public class MyJsonTransformer {
        public static void main(String[] args) throws Exception {
            List<Object> specs = JsonUtils.classpathToList("/spec.json");
            Chainr chainr = Chainr.fromSpec(specs);
     
            Object inputJSON = JsonUtils.classpathToObject("/input.json");
            Object transformedOutput = chainr.transform(inputJSON);
            System.out.println(JsonUtils.toPrettyJsonString(transformedOutput));
        }
    }
    

    And a jolt remover spec file like this:

    [
      {
        "operation": "remove",
        "spec": {
          "info": {
            "processMonitor": {
              "processList": ""
              }
            }
          }
        }
    ]
    

    You can try JOLT online with your input and the spec above here. Pretty neat.
    The JSON and spec can be defined inline as well. I have not tested this end to end.