notationWithoutTrailingCommas function

String notationWithoutTrailingCommas(
  1. String raw
)

raw (a list or a record as written) without the comma after a last item ([1, 2, ], {"a": 1,}), which JSON does not read. What is in quotes is left as it is.

Implementation

String notationWithoutTrailingCommas(String raw) {
  if (!raw.contains(',')) return raw;
  final out = StringBuffer();
  String? quote;
  for (var i = 0; i < raw.length; i++) {
    final c = raw[i];
    if (quote != null) {
      out.write(c);
      if (c == r'\' && i + 1 < raw.length) {
        out.write(raw[++i]);
      } else if (c == quote) {
        quote = null;
      }
      continue;
    }
    if (c == '"') quote = c;
    if (c == ',') {
      var j = i + 1;
      while (j < raw.length && raw[j].trim().isEmpty) {
        j++;
      }
      if (j < raw.length && (raw[j] == ']' || raw[j] == '}')) continue;
    }
    out.write(c);
  }
  return out.toString();
}