0

Input

{
    "email" : "[email protected]"
},{
    "email" : "[email protected]"
},{
    "email" : "[email protected]"
},{
    "email" : "[email protected]"
},

Expected output

{
    "email" : "[email protected]"
},{
    "email" : "[email protected]"
},
  1. Remove duplicates

  2. maintain format

  3. appended last comma.

The problem is sometimes the input is not a proper JSON and also it's not sure that comma should be always present at the end. I need to remove only duplicate key value pairs from the input, the rest should remain the same.

I tried this way.

if (maxIndex > 0) {
    try {
        singleElementTemplate = dao.resolveObjectDataStringSinglePass(tmdtId, sourceTagHandle,
                maxIndex);

        String jsonText = singleElementTemplate.trim();

        if (!jsonText.startsWith("[") && !jsonText.endsWith("]")) {
            jsonText = "[" + jsonText + "]";
        }

        JSONArray jsonArr = new JSONArray(jsonText);

        Set<String> seen = new LinkedHashSet<>();
        JSONArray finalJsonArr = new JSONArray();

        for (int i = 0; i < jsonArr.length(); i++) {
            JSONObject obj = jsonArr.getJSONObject(i);
            if (seen.add(obj.toString())) {
                finalJsonArr.put(obj);
            }
        }

        StringBuilder formattedResult = new StringBuilder();
        for (int i = 0; i < finalJsonArr.length(); i++) {

            // Appends formatted JSON (2-space indent)
            formattedResult.append(finalJsonArr.getJSONObject(i).toString(2));
            if (i < finalJsonArr.length() - 1) {
                formattedResult.append(",\n");
            }
        }

        singleElementTemplate = formattedResult.toString().trim();

    } catch (JSONException ex1) {
    }
} else {}

But the output is like this.

{"email" : "[email protected]"},
{"email" : "[email protected]"}

Note: I can't use regex as the JSON could also contain nested {}.

2
  • 1
    what have you tried, and where are you stuck? provide all relevant information, not just an assignment. Commented Nov 13 at 6:26
  • 2
    “The problem is sometimes the input is not a proper JSON” —Then you can’t use JSON classes to read it. You will have to write your own parser, from scratch. Do not try to fix the input with regular expressions; that may work for a few cases but is guaranteed to fail eventually. Commented Nov 13 at 15:23

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.