extractJsonFromText function
Extracts a valid JSON string from a block of text.
This function looks for a JSON block between ```json
and ```
markers
and attempts to extract and clean the JSON content.
Parameters:
text
: The raw text containing the JSON.
Returns: A valid JSON string extracted from the input text.
Throws:
- FormatException if valid JSON is not found within the text.
Implementation
String extractJsonFromText(String text) {
// Find the position of the first ```json``` block
final jsonStart = text.indexOf('```json');
// Find the position of the closing ```
final jsonEnd = text.indexOf('```', jsonStart + 6);
// Check if both the start and end markers were found
if (jsonStart != -1 && jsonEnd != -1) {
// Extract the potential JSON text between the markers
String jsonString = text.substring(jsonStart + 6, jsonEnd).trim();
// Now clean up the JSON string to remove any unwanted characters
// Ensure the string starts with '{' and ends with '}' (valid JSON structure)
final validJsonStart = jsonString.indexOf('{');
final validJsonEnd = jsonString.lastIndexOf('}');
if (validJsonStart != -1 && validJsonEnd != -1) {
jsonString = jsonString.substring(validJsonStart, validJsonEnd + 1);
return jsonString;
} else {
throw const FormatException(
"Valid JSON not found within the extracted text");
}
} else {
throw const FormatException("JSON format not found in the response");
}
}