mirror of
https://github.com/foss42/apidash.git
synced 2025-12-02 10:49:49 +08:00
Refactor DashBot
This commit is contained in:
30
lib/dashbot/utils/safe_parse_json_message.dart
Normal file
30
lib/dashbot/utils/safe_parse_json_message.dart
Normal file
@@ -0,0 +1,30 @@
|
||||
import 'dart:convert';
|
||||
|
||||
/// Lightweight JSON parser helper to avoid adding dependencies.
|
||||
/// Intended for parsing AI agent structured outputs that may be wrapped
|
||||
/// in markdown code fences or include extra prose.
|
||||
class MessageJson {
|
||||
static Map<String, dynamic> safeParse(String input) {
|
||||
// Try strict JSON first
|
||||
try {
|
||||
return _parseJson(input);
|
||||
} catch (_) {
|
||||
// If input looks like markdown fenced block containing JSON, try to extract
|
||||
final start = input.indexOf('{');
|
||||
final end = input.lastIndexOf('}');
|
||||
if (start != -1 && end != -1 && end > start) {
|
||||
final slice = input.substring(start, end + 1);
|
||||
return _parseJson(slice);
|
||||
}
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
|
||||
static Map<String, dynamic> _parseJson(String s) {
|
||||
final decoded = jsonDecode(s);
|
||||
if (decoded is Map<String, dynamic>) {
|
||||
return decoded;
|
||||
}
|
||||
return {};
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user