isJson static method
Returns true if value appears to be valid JSON.
If shouldTestDecode is true, actually attempts to decode to verify.
If shouldAllowEmpty is true, treats '{}' and '[]' as valid JSON
(defaults to false for backwards compatibility).
Audited: 2026-06-12 11:26 EDT
Implementation
@useResult
static bool isJson(
String? value, {
bool shouldTestDecode = false,
bool shouldAllowEmpty = false,
}) {
if (value == null || value.length < 2) return false;
final String trimmed = value.trim();
final bool isObject = trimmed.startsWith('{') && trimmed.endsWith('}');
final bool isArray = trimmed.startsWith('[') && trimmed.endsWith(']');
if (!isObject && !isArray) return false;
if (!_hasValidJsonContent(
trimmed,
isObject: isObject,
shouldAllowEmpty: shouldAllowEmpty,
)) {
return false;
}
if (!shouldTestDecode) return true;
try {
return dc.jsonDecode(value) != null;
} on FormatException catch (e, stackTrace) {
// ignore: saropa_lints/avoid_print_error, saropa_lints/avoid_debug_print, saropa_lints/avoid_stack_trace_in_production -- intentional diagnostic logging; debugPrint is stripped in release builds
debugPrint('JsonUtils.isJson testDecode failed: $e\n$stackTrace');
return false;
}
}