0

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

1
  • 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. Commented Aug 14, 2022 at 14:44

1 Answer 1

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"
            }
        ]
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

This is not working
Is there any exception thrown? Because I tested it, and it worked on my machine.
Are you sure it worked for you? For me no exception occurred yet the array was not removed

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.