extractJSON method

String extractJSON(
  1. String text
)

Extract JSON from potentially mixed text

Implementation

String extractJSON(String text) {
  final trimmed = text.trim();

  // First, try to find a complete JSON object
  final completeJson = _findCompleteJSON(trimmed);
  if (completeJson != null) {
    return completeJson;
  }

  // Fallback: Try to find JSON object boundaries
  final startIndex = trimmed.indexOf('{');
  final endIndex = trimmed.lastIndexOf('}');

  if (startIndex != -1 && endIndex != -1 && startIndex < endIndex) {
    final jsonSubstring = trimmed.substring(startIndex, endIndex + 1);
    try {
      jsonDecode(jsonSubstring);
      return jsonSubstring;
    } catch (_) {
      // Not valid JSON, continue to other methods
    }
  }

  // Try to find JSON array boundaries
  final arrayStartIndex = trimmed.indexOf('[');
  final arrayEndIndex = trimmed.lastIndexOf(']');

  if (arrayStartIndex != -1 &&
      arrayEndIndex != -1 &&
      arrayStartIndex < arrayEndIndex) {
    final jsonSubstring =
        trimmed.substring(arrayStartIndex, arrayEndIndex + 1);
    try {
      jsonDecode(jsonSubstring);
      return jsonSubstring;
    } catch (_) {
      // Not valid JSON
    }
  }

  // If no clear JSON boundaries, check if the entire text might be JSON
  if (trimmed.startsWith('{') || trimmed.startsWith('[')) {
    try {
      jsonDecode(trimmed);
      return trimmed;
    } catch (_) {
      // Not valid JSON
    }
  }

  // Log the text that couldn't be parsed
  _logger.error(
      'Failed to extract JSON from text: ${trimmed.length > 200 ? trimmed.substring(0, 200) : trimmed}...');
  throw StructuredOutputError.extractionFailed(
      'No valid JSON found in the response');
}