karatelabs/karate · warning

fromString JSON parse failed

Error message

fromString JSON parse failed: {}

What it means

karate's fromString (JS string-to-value coercion in KarateJsUtils) attempts JSON.parse-equivalent conversion when the text 'looks like JSON' (StringUtils.looksLikeJson). If Json.of(text) throws, the warning 'fromString JSON parse failed' is logged and the ORIGINAL string is returned unchanged — it is a graceful fallback, not a thrown exception.

Solutions

  1. Fix the input string so it is strictly valid JSON (double-quote keys/strings, no trailing commas/comments).
  2. Validate the string with a JSON linter/JSON.parse before passing it to fromString.
  3. If you truly have a JS object literal or JSON5, convert it to strict JSON first (e.g. JSON.stringify of the evaluated literal).
  4. Check the logged e.getMessage() in the warning — it pinpoints the exact parse offset/syntax problem.
  5. Accept the fallback if you want raw text on failure; verify downstream code handles a String instead of a Map/List.

Example fix

// before
var cfg = karate.fromString("{name: 'x', enabled: true,}"); // JS literal + trailing comma -> warning, returns string

// after
var cfg = karate.fromString('{"name":"x","enabled":true}'); // strict JSON -> real map
Defensive patterns

Strategy: validation

Validate before calling

// JS: strict JSON check before fromString
function isStrictJson(s) {
  try { JSON.parse(s); return true; } catch (e) { return false; }
}
if (isStrictJson(text)) { var val = karate.fromString(text); }

Type guard

function isParsedObject(v) { return v !== null && typeof v === 'object'; }

Try / catch

// fromString does not throw on bad JSON — it returns the raw string; narrow the result
var val = karate.fromString(text);
if (typeof val === 'string') {
  // parse failed; handle or rethrow with context
  throw new Error('not valid JSON: ' + text);
}

Prevention

When it happens

Trigger: Passing a string that passes the looksLikeJson heuristic (e.g. starts with '{', '[', or is quoted) but is not valid JSON to karate.fromString(...) or APIs that internally use this coercion — e.g. malformed JSON with trailing commas, single quotes, unquoted keys, comments, or truncated JSON.

Common situations: Reading config/fixture files that are JSON-ish but not strictly valid JSON; embedding JS object-literal syntax ({key: 'v'}) and expecting a map back; copy-pasted JSON with smart quotes or trailing commas; partial JSON produced by string concatenation.

Understand the failure class

Background: JSON parse error: "Unexpected token" / "not valid JSON" / "failed to parse" — what JSON parsers are really complaining about — this error's family across 45 libraries.

Related errors


AI-assisted analysis of karatelabs/karate@a22eb90246 (2026-09-12). Data as JSON: /api/errors/047ecefb4b270ca4. Report an issue: GitHub.

Appendix: source

Thrown at karate-core/src/main/java/io/karatelabs/core/KarateJsUtils.java:792

     * Parse a string as JSON, XML, or return as-is.
     * - If the string looks like JSON (starts with { or [), parse as JSON
     * - If the string looks like XML (starts with <), parse as XML
     * - Otherwise, return the string unchanged
     */
    static JavaInvokable fromString() {
        return args -> {
            if (args.length == 0 || args[0] == null) {
                return null;
            }
            String text = args[0].toString();
            if (text.isEmpty()) {
                return text;
            }
            if (StringUtils.looksLikeJson(text)) {
                try {
                    return Json.of(text).value();
                } catch (Exception e) {
                    logger.warn("fromString JSON parse failed: {}", e.getMessage());
                    return text;
                }
            } else if (StringUtils.isXml(text)) {
                try {
                    return Xml.toXmlDoc(text);
                } catch (Exception e) {
                    logger.warn("fromString XML parse failed: {}", e.getMessage());
                    return text;
                }
            }
            return text;
        };
    }

    /**
     * Auto-detect MIME type from data object.
     */
    static String detectMimeType(Object obj) {

View on GitHub (pinned to a22eb90246)