makeValidJson static method
Implementation
static String makeValidJson(String input) {
// Replace 'undefined' with null
input = input.replaceAll(RegExp(r'\bundefined\b'), 'null');
// Add double quotes around keys, ignoring URLs (http: or https:)
input = input.replaceAllMapped(
RegExp(r'(\b(?!http|https)[a-zA-Z0-9_]+)(?=:)', multiLine: true),
(match) => '"${match.group(0)}"',
);
// Add double quotes around string values while ignoring URLs
input = input.replaceAllMapped(
RegExp(r':\s*([^"{\[\],\s][^,}\]]*)'),
(match) {
final value = match.group(1);
// If value starts with http or https, don't wrap it in quotes
if (value != null &&
(value.startsWith('http:') || value.startsWith('https:'))) {
return ':"$value"'; // Don't add quotes for URLs
}
// Otherwise, quote it normally
return ': "$value"';
},
);
try {
// Parse to ensure it's valid JSON
final jsonObject = jsonDecode(input);
return const JsonEncoder.withIndent(' ').convert(jsonObject); // Pretty-printed JSON
} on FormatException catch (e) {
return 'FormatException: ${e.toString()}';
} on Exception catch (e) {
return 'Error: ${e.toString()}';
}
}