Skip to content

Instantly share code, notes, and snippets.

@gkhays
Last active July 18, 2018 12:03
Show Gist options
  • Save gkhays/4fe1e6193e62b1f2cad3bd4b00f16c92 to your computer and use it in GitHub Desktop.
Save gkhays/4fe1e6193e62b1f2cad3bd4b00f16c92 to your computer and use it in GitHub Desktop.
Remove an attribute or element from a JSON array during enumeration

Remove a JSON Key While Iterating

I want to remove any JSON key/value pairs wherein the value is the empty string "" or is the string literal null. However Java enumerations don't like that and will throw a ConcurrentModificationException if you attempt to remove the key and value.

JSONArray ja = loadJSONArray();
JSONObject firstJSON = ja.getJSONObject(0);
Iterator<?> iter = firstJSON.keys();
for (int i = 0; i < ja.length(); i++) {
	JSONObject json = ja.getJSONObject(i);
	while (iter.hasNext()) {
		String key = iter.next().toString();
		if (json.getString(key).equals("null")) {
			json.remove(key);
		}
	}
}

Output:

Exception in thread "main" java.util.ConcurrentModificationException
	at java.util.LinkedHashMap$LinkedHashIterator.nextNode(LinkedHashMap.java:711)
	at java.util.LinkedHashMap$LinkedKeyIterator.next(LinkedHashMap.java:734)
	at JSONKeyRemover.removeKeyWhileIterating(JSONKeyRemover.java:32)
	at JSONKeyRemover.main(JSONKeyRemover.java:69)

I ended up copying the JSON array into a Java collection and used the JSONObject.names() method to obtain a JSONArray of keys.

JSONArray nameArray = firstJSON.names();
List<String> keyList = new ArrayList<String>();
for (int i = 0; i < nameArray.length(); i++) {
	keyList.add(nameArray.get(i).toString());
}

for (int i = 0; i < ja.length(); i++) {
	for (String key : keyList) {
		JSONObject json = ja.getJSONObject(i);
		if (json.getString(key).equals("null")) {
			json.remove(key);
		}
	}
}

Output:

Before
[
  {
    "badid": "null",
    "goodid": "1"
  },
  {
    "badid": "2",
    "goodid": "3"
  }
]
After
[
  {"goodid": "1"},
  {
    "badid": "2",
    "goodid": "3"
  }
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment