Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove keys from anywhere in a JSON string without deserialization

Without deserializing and reserializing the following deeply-nested JSON string (if this is possible), how to remove any key with the name "REMOVEME" from any nested level?

Tried:

Reluctantly tried deserializing to JsonObject / LinkedHashMap to traverse the structure with node.remove(e.getKey()) on offending keys, but Gson throws concurrent modification exceptions, and Jackson requires full deserialization.

Before:

{
    "a": {
        "REMOVEME" : "unwanted",
        "b": {
            "REMOVEME" : "unwanted",
            "c": {
                "d": {
                    "REMOVEME" : "unwanted",
                    "something": "default",
                    "e": {
                        "f": {
                            "REMOVEME" : "unwanted",
                            "g": {
                                "REMOVEME" : "unwanted",        
                                "h": {
                                    ... ,

After:

{
    "a": {
        "b": {
            "c": {
                "d": {
                    "something": "default",
                    "e": {
                        "f": {
                            "g": {
                                "h": {
                                    ... ,
like image 748
Drakes Avatar asked Oct 21 '25 02:10

Drakes


1 Answers

I'm not sure the way you are trying to delete the property from node, but it is possible to delete the property i did it by using jackson

String json = "{\n" + 
            "    \"a\": {\n" + 
            "        \"REMOVEME\" : \"unwanted\",\n" + 
            "        \"b\": {\n" + 
            "            \"REMOVEME\" : \"unwanted\"\n" + 
            "        }\n" + 
            "    }\n" + 
            "}";

    JsonNode node = objectMapper.readTree(json);
    ObjectNode node1 = (ObjectNode) node.get("a");

    node1.remove("REMOVEME");
    System.out.println(node1);  // {"b":{"REMOVEME":"unwanted"}}
    System.out.println(node);   // {"a":{"b":{"REMOVEME":"unwanted"}}}
like image 94
Deadpool Avatar answered Oct 23 '25 16:10

Deadpool



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!