Skip to content

Instantly share code, notes, and snippets.

@ozzi-
Created December 3, 2020 09:09
Show Gist options
  • Save ozzi-/4eefe81a224f4fbfaaf415010fd213ee to your computer and use it in GitHub Desktop.
Save ozzi-/4eefe81a224f4fbfaaf415010fd213ee to your computer and use it in GitHub Desktop.
removes trailing commas in JSON strings
// Input:
// [
// {
// "f00" : "bar",
// "info" : "this comma to my right is wrong",
// },
// {
// "f00" : "bar",
// "info" : "the comma on the line below is wrong too!"
// },
// ]
public static String stripTrailingJSONCommas(String json) {
String findTrailingComma = "(\\,)(?!\\s*?[\\{\\[\\\"\\\'\\w])"; // = (\,)(?!\s*?[\{\[\"\'\w])
Pattern p = Pattern.compile(findTrailingComma);
Matcher m = p.matcher(json);
if (m.find()) {
json = m.replaceAll("");
}
return json;
}
// Output:
// [
// {
// "f00" : "bar",
// "info" : "this comma to my right is wrong"
// },
// {
// "f00" : "bar",
// "info" : "the comma on the line below is wrong too!"
// }
// ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment