1

I am trying to remove JSON array from a JSON file using org.json library

I am trying to remove webAutomation JSON array from the JSON file as follows

{
    "instructor": "Test_Instructor",
    "url": "www.google.com",
    "services": "Test Automation Service",
    "expertise": "Testing",
    "linkedIn": "linkedIn",
    "courses": {
        "webAutomation": [
            {
                "price": "500",
                "courseTitle": "Selenium"
            },
            {
                "price": "333",
                "courseTitle": "Protractor"
            }
        ],
        "apiAutomation": [
            {
                "price": "344.00",
                "courseTitle": "Rest Assured API Automation"
            }
        ],
        "mobileAutomation": [
            {
                "price": "4555",
                "courseTitle": "Appium"
            }
        ]
    }
}

I tried following code. Here str has JSON file

JSONObject jsonObject = new JSONObject(str);
jsonObject.getJSONObject("courses").getJSONArray("webAutomation");
System.out.println("after removal");
String str2 = mapper.writeValueAsString(jsonObject);
System.out.println(str2);

This is removing the whole JSON object instead of just JSON Array. The output is {"empty":false} Please help

nikhil udgirkar
  • 367
  • 1
  • 7
  • 23
  • Why are you using two JSON parsing libraries? You also didn't actually remove anything in your bit of code. `getJSONArray` simply returns the element. – Sotirios Delimanolis Aug 14 '22 at 14:44

1 Answers1

1

You can use remove method in org.json.JSONObject#remove.

JSONObject json = new JSONObject(str);
json.getJSONObject("courses").remove("webAutomation");
System.out.println(json);

The output will be:

{
    "instructor": "Test_Instructor",
    "url": "www.google.com",
    "services": "Test Automation Service",
    "expertise": "Testing",
    "linkedIn": "linkedIn",
    "courses": {
        "apiAutomation": [
            {
                "price": "344.00",
                "courseTitle": "Rest Assured API Automation"
            }
        ],
        "mobileAutomation": [
            {
                "price": "4555",
                "courseTitle": "Appium"
            }
        ]
    }
}