cleanJsonResponse static method

String? cleanJsonResponse(
  1. String? value
)

Cleans a JSON response string by stripping outer double-quotes and unescaping any inner escaped quotes (\").

Correctly handles strings that contain escaped inner quotes, e.g.: '"hello \"world\""''hello "world"'.

Implementation

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) {
    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();
}