decodeExactJson function

Map<String, Object?> decodeExactJson(
  1. String raw
)

Validate numeric round trips before Dart's JSON decoder can round them.

Implementation

Map<String, Object?> decodeExactJson(String raw) {
  final tokens = RegExp(r'"(?:[^"\\]|\\.)*"|-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?');
  final low = BigInt.parse('-9223372036854775808');
  final high = BigInt.parse('9223372036854775807');
  for (final match in tokens.allMatches(raw)) {
    final token = match.group(0)!;
    if (token.startsWith('"')) continue;
    if (token.contains(RegExp('[.eE]'))) {
      final value = double.parse(token);
      if (!value.isFinite || _decimal(token) == null || _decimal(token) != _decimal(jsonEncode(value))) {
        throw LosslessNumberException();
      }
    } else {
      final integer = BigInt.parse(token);
      if (integer < low || integer > high) throw LosslessNumberException();
    }
  }
  return (jsonDecode(raw) as Map<String, dynamic>).cast<String, Object?>();
}