cleanJsonResponse static method
Returns a cleaned version of the JSON response value by stripping
outer double-quotes and unescaping any inner escaped quotes (\"),
or null if the result is empty.
Correctly handles strings that contain escaped inner quotes, e.g.:
'"hello \"world\""' → 'hello "world"'.
Audited: 2026-06-12 11:26 EDT
Implementation
@useResult
static String? cleanJsonResponse(String? value) {
if (value == null || value.isEmpty) return null;
final String trimmed = value.trim();
if (trimmed.isEmpty) return null;
// Detect outer quotes BEFORE unescaping inner ones.
if (trimmed.startsWith('"') && trimmed.endsWith('"') && trimmed.length >= 2) {
// Code-unit substring, not the grapheme-indexed substringSafe: the quote
// detection and `trimmed.length` are code-unit measures. With substringSafe
// a quoted value containing an astral grapheme (e.g. "🎉") clamped the end
// index to the grapheme count and left the closing quote in place.
final String inner = trimmed.substring(1, trimmed.length - 1);
return inner.replaceAll(r'\"', '"').nullIfEmpty();
}
// No outer quotes — just unescape any escaped quotes present.
return trimmed.replaceAll(r'\"', '"').nullIfEmpty();
}