jsonDecodeMap function

Map<String, dynamic> jsonDecodeMap(
  1. dynamic json
)

Decodes a JSON string into a Map<String, dynamic>, always returning a map.

Returns an empty map for invalid or empty input.

final result = jsonDecodeMap('{"key": "value"}');
print(result); // {key: value}

final emptyResult = jsonDecodeMap('');
print(emptyResult); // {}

@ai Use when you need a map result regardless of input validity. Handle errors externally.

Implementation

Map<String, dynamic> jsonDecodeMap(final dynamic json) {
  if (json case final Map<String, dynamic> map) return map.isEmpty ? {} : map;
  final jsonString = jsonDecodeString(json);
  if (jsonString.isEmpty) return {};
  return switch (jsonDecode(jsonString)) {
    final Map<String, dynamic> map => map,
    _ => {},
  };
}