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) {
// Structured log instead of debugPrint, so the stack trace is not printed
// to stdout; the caller still gets false as the failure signal.
// ignore: saropa_lints/avoid_stack_trace_in_production -- false positive: dart:developer log() is not user-visible
log('JsonUtils.isJson testDecode failed', error: e, stackTrace: stackTrace);
return false;
}
}