isJson static method

bool isJson(
  1. String? value, {
  2. bool testDecode = false,
  3. bool allowEmpty = false,
})

Checks if a string appears to be valid JSON.

Args:

  • value: The string to check.
  • testDecode: If true, actually attempts to decode to verify.
  • allowEmpty: If true, treats '{}' and '[]' as valid JSON. Defaults to false for backwards compatibility.

Returns: True if the string appears to be valid JSON.

Implementation

static bool isJson(String? value, {bool testDecode = false, bool allowEmpty = 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 (isObject && !trimmed.contains(':')) {
    // Empty object '{}' is valid JSON only if allowEmpty is true
    if (!allowEmpty || trimmed != '{}') return false;
  }
  if (isArray && trimmed == '[]') {
    // Empty array '[]' is valid JSON only if allowEmpty is true
    if (!allowEmpty) return false;
  }
  if (!testDecode) return true;
  try {
    return dc.jsonDecode(value) != null;
  } on Object catch (e, stackTrace) {
    // ignore: avoid_print_error - debugPrint is appropriate for utility packages (stripped in release builds, no external dependencies)
    debugPrint('JsonUtils.isJson testDecode failed: $e\n$stackTrace');
    return false;
  }
}