Find Duplicate Key Value pairs across all JSON Objects in a JSON file

505 Views Asked by At

I have a JSON file like

{
    "object1": {
        "key_1": "value_1",
        "key_2": "value_2",
        "key_3": "value_3"
    },
    "object2": {
        "key_1": "value_1",
        "key_4": "value_4"
    }
}

I have to find out duplicate key value pairs from these JSON objects, e.g: first object "object1", I have "key_1":"value_1" which is also present in "object2", in that case I need to print message for containing duplicate key value pairs in the JSON file.

I tried to read each key value pair and store same key value pair in HashMap, before storing, I am checking whether same key value pair already exists in the HashMap or not, once I encountered any duplicate key value pair, I am printing message.

My question is, for achieving same thing, do we have any open source java library?

1

There are 1 best solutions below

4
Raymond Choi On

Library Josson can transform the JSON.

https://github.com/octomix/josson

// Deserialization
Josson josson = Josson.fromJsonString(
    "{" +
    "    \"object1\": {" +
    "        \"key_1\": \"value_1\"," +
    "        \"key_2\": \"value_2\"," +
    "        \"key_3\": \"value_3\"," +
    "        \"key_5\": \"value_5\"," +
    "        \"key_6\": \"value_6\"" +
    "    }," +
    "    \"object2\": {" +
    "        \"key_1\": \"value_1\"," +
    "        \"key_2\": \"value_2\"," +
    "        \"key_4\": \"value_4\"," +
    "        \"key_5\": \"value_5\"" +
    "    }" +
    "}");

// Transform    
JsonNode node = josson.getNode(
    "**.entries().map(key::value).group(obj:?).[elements.size()>1]*.obj");
System.out.println(node.toPrettyString());

Output

[ {
  "key_1" : "value_1"
}, {
  "key_2" : "value_2"
}, {
  "key_5" : "value_5"
} ]