sanitize static method

Object? sanitize(
  1. Object? value, {
  2. int depth = 0,
})

Converts any value to a JSON-compatible structure.

Implementation

static Object? sanitize(Object? value, {int depth = 0}) {
  if (depth > 24) return value.toString();
  if (value == null || value is num || value is bool || value is String) {
    return value;
  }
  if (value is DateTime) return value.toIso8601String();
  if (value is Uint8List) return '<binary ${humanBytes(value.length)}>';
  if (value is FormData) return formDataToMap(value);
  if (value is MultipartFile) {
    return '<file ${value.filename ?? 'unnamed'} ยท ${humanBytes(value.length)}>';
  }
  if (value is Map) {
    final result = <String, dynamic>{};
    value.forEach((key, dynamic item) {
      result['$key'] = sanitize(item, depth: depth + 1);
    });
    return result;
  }
  if (value is Iterable) {
    return value.map((dynamic e) => sanitize(e, depth: depth + 1)).toList();
  }
  try {
    // ignore: avoid_dynamic_calls
    return sanitize((value as dynamic).toJson() as Object?, depth: depth + 1);
  } catch (_) {
    return value.toString();
  }
}