parseFirstJsonBlock static method

Object? parseFirstJsonBlock(
  1. String text
)

Parses the first valid JSON object or array found in text.

This method looks for JSON patterns, handling:

  • Markdown code blocks (e.g., json ... )
  • Raw JSON objects/arrays directly in text

Returns null if no valid JSON is found.

Implementation

static Object? parseFirstJsonBlock(String text) {
  final String? markdownBlock = _extractMarkdownJson(text);
  if (markdownBlock != null) {
    try {
      return jsonDecode(markdownBlock);
    } on FormatException catch (_) {}
  }

  final int firstBrace = text.indexOf('{');
  final int firstBracket = text.indexOf('[');

  var start = -1;
  if (firstBrace != -1 && firstBracket != -1) {
    start = firstBrace < firstBracket ? firstBrace : firstBracket;
  } else if (firstBrace != -1) {
    start = firstBrace;
  } else if (firstBracket != -1) {
    start = firstBracket;
  }

  if (start == -1) return null;

  final String input = text.substring(start);
  try {
    return jsonDecode(input);
  } on FormatException catch (_) {
    final String? result = _extractBalancedJson(input);
    if (result != null) {
      try {
        return jsonDecode(result);
      } on FormatException catch (_) {
        return null;
      }
    }
    return null;
  }
}