toPrettyJson function
Converts a dynamic input into a formatted JSON string.
This function handles both String
and Map
input types.
- If the input is a JSON string, it decodes and formats it.
- If the input is a
Map
, it directly converts it to a formatted JSON string. - If the input is
null
or an invalid type, it returns an error message.
Parameters:
input
(dynamic
): The JSON string or Map to convert.
Returns:
String
: A prettified JSON string or an error message.
Implementation
String toPrettyJson(dynamic input) {
Map<dynamic, dynamic>? jsonMap;
if (input == null) {
return '{}';
}
if (input is String) {
if (input.isEmpty) {
return '{}';
}
// If input is a JSON string, decode it into a Map
try {
jsonMap = json.decode(input);
} catch (e) {
return 'Error decoding JSON string: $e';
}
} else if (input is Map) {
// If input is already a Map, use it directly
jsonMap = input;
} else {
// return 'Invalid input type: expected String or Map';
return '';
}
if (jsonMap == null) {
return '';
}
try {
// Use JsonEncoder with 2-space indentation to make the JSON pretty
const jsonEncoder = JsonEncoder.withIndent(' ');
// Convert the Map object into a pretty JSON string
return jsonEncoder.convert(jsonMap);
} catch (e) {
// If there's an error during conversion, return an error message
// return 'Error converting to JSON: $e';
return '';
}
}