Dart JSON decode with path-aware errors

Dart
import 'dart:convert';

Object? parseJson(String source, {String label = 'payload'}) {
  try {
    return jsonDecode(source);
  } on FormatException catch (e) {
    final excerpt = source.length > 60 ? '${source.substring(0, 60)}...' : source;
    final where = e.offset == null ? '' : ' at offset ${e.offset}';
    throw FormatException('Invalid JSON in $label$where: ${e.message}. Near: $excerpt');
  }
}

Map<String, dynamic> parseJsonObject(String source) {
  final value = parseJson(source);
  if (value is! Map<String, dynamic>) {
    throw FormatException('Expected a JSON object, got ${value.runtimeType}');
  }
  return value;
}