3

I have generated below Json using Jackson lib in Java:

{
    "name": "name1",
    "version": "0.0.1",
    "storage": {
        "db": {
            "test_field1": "STRING",
            "t_dlm1": "STRING",
            "test_field2": "STRING",
            "t_dlm2": "STRING"

        },
        "test": {
            "test11": "STRING",
            "test2": {
                "test3": "0",
                "r_dlm4": "0"
            },
            "test5": {
                "test6": "0",
                "h_dlm7": "0"
            }
        },
        "test8": {
            "test9": "STRING",
            "f_dlm10": "STRING"
        }
    }
}

Now I am a requirement of remove those json node or field (key and value) that contains "dlm" word.

I tried remove and removeAll method , with that i am able to remove specific field but need to pass full exact name of field.

I am bit new here please guide me here how to remove json node if field name contains "dlm" word

expected json:

   {
"name": "name1",
"version": "0.0.1",
"storage": {
    "db": {
        "test_field1": "STRING",

        "test_field2": "STRING"


    },
    "test": {
        "test11": "STRING",
        "test2": {
            "test3": "0"

        },
        "test5": {
            "test6": "0"

        }
    },
    "test8": {
        "test9": "STRING"

    }
}
}
pcoates
  • 2,102
  • 1
  • 9
  • 20
Ron
  • 51
  • 3

1 Answers1

0

I think you'll need to loop around all the nodes checking for a key containing 'dlm'.

You could make use of jayway's JsonPath to get a list of all the paths using the Option.AS_PATH_LIST, then loop around those and remove any containing dlm.

    Configuration conf = Configuration.builder()
            .options(Option.AS_PATH_LIST).build();

    DocumentContext parsedJson = JsonPath.using(conf).parse(json);
    List<String> pathList = parsedJson.read("$..*");

    for (String path : pathList) {
        if (path.contains("dlm")) {
            parsedJson.delete(path);
        }
    }

    String result = parsedJson.jsonString();

I suspect you could just use a suitable path to select all the elements with dlm. You can apply filters and use regex, although I can't see how to use the element name in the filter (i.e. something like /name() in xpath).

Note: if you've got nested nodes with 'dlm' the above code may well remove the outer node, before trying to remove the inner one, so you might get a path not found exception.

JsonPath brings in json-smart as a dependency and uses that by default. If you want it to use jackson you have to tell it. e.g.:

    Configuration conf = Configuration.builder()
            .jsonProvider(new JacksonJsonProvider())
            .mappingProvider(new JacksonMappingProvider())
            .options(Option.AS_PATH_LIST)
            .build();
pcoates
  • 2,102
  • 1
  • 9
  • 20