{"record":{"id":"047ecefb4b270ca4","repo":"karatelabs/karate","slug":"fromstring-json-parse-failed","errorCode":null,"errorMessage":"fromString JSON parse failed: {}","messagePattern":"fromString JSON parse failed: (.+?)","errorType":"console","errorClass":null,"httpStatus":null,"severity":"warning","filePath":"karate-core/src/main/java/io/karatelabs/core/KarateJsUtils.java","lineNumber":792,"sourceCode":"     * Parse a string as JSON, XML, or return as-is.\n     * - If the string looks like JSON (starts with { or [), parse as JSON\n     * - If the string looks like XML (starts with &lt;), parse as XML\n     * - Otherwise, return the string unchanged\n     */\n    static JavaInvokable fromString() {\n        return args -> {\n            if (args.length == 0 || args[0] == null) {\n                return null;\n            }\n            String text = args[0].toString();\n            if (text.isEmpty()) {\n                return text;\n            }\n            if (StringUtils.looksLikeJson(text)) {\n                try {\n                    return Json.of(text).value();\n                } catch (Exception e) {\n                    logger.warn(\"fromString JSON parse failed: {}\", e.getMessage());\n                    return text;\n                }\n            } else if (StringUtils.isXml(text)) {\n                try {\n                    return Xml.toXmlDoc(text);\n                } catch (Exception e) {\n                    logger.warn(\"fromString XML parse failed: {}\", e.getMessage());\n                    return text;\n                }\n            }\n            return text;\n        };\n    }\n\n    /**\n     * Auto-detect MIME type from data object.\n     */\n    static String detectMimeType(Object obj) {","sourceCodeStart":774,"sourceCodeEnd":810,"githubUrl":"https://github.com/karatelabs/karate/blob/a22eb90246d958d15a47bf436693d0121ad2812d/karate-core/src/main/java/io/karatelabs/core/KarateJsUtils.java#L774-L810","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","solutions":["Fix the input string so it is strictly valid JSON (double-quote keys/strings, no trailing commas/comments).","Validate the string with a JSON linter/JSON.parse before passing it to fromString.","If you truly have a JS object literal or JSON5, convert it to strict JSON first (e.g. JSON.stringify of the evaluated literal).","Check the logged e.getMessage() in the warning — it pinpoints the exact parse offset/syntax problem.","Accept the fallback if you want raw text on failure; verify downstream code handles a String instead of a Map/List."],"exampleFix":"// before\nvar cfg = karate.fromString(\"{name: 'x', enabled: true,}\"); // JS literal + trailing comma -> warning, returns string\n\n// after\nvar cfg = karate.fromString('{\"name\":\"x\",\"enabled\":true}'); // strict JSON -> real map","handlingStrategy":"validation","validationCode":"// JS: strict JSON check before fromString\nfunction isStrictJson(s) {\n  try { JSON.parse(s); return true; } catch (e) { return false; }\n}\nif (isStrictJson(text)) { var val = karate.fromString(text); }","typeGuard":"function isParsedObject(v) { return v !== null && typeof v === 'object'; }","tryCatchPattern":"// fromString does not throw on bad JSON — it returns the raw string; narrow the result\nvar val = karate.fromString(text);\nif (typeof val === 'string') {\n  // parse failed; handle or rethrow with context\n  throw new Error('not valid JSON: ' + text);\n}","preventionTips":["Keep fixtures strictly valid JSON: double quotes, no trailing commas, no comments.","Lint/parse test data files at build time so malformed JSON never reaches fromString.","Convert JS object literals with JSON.stringify(...) before coercion.","Check the warning's e.getMessage() immediately — it names the exact syntax error."],"tags":["json","parsing","karate","fallback"],"backgroundTag":"json-parse-error","analyzedSha":"a22eb90246d958d15a47bf436693d0121ad2812d","analyzedAt":"2026-09-12T09:01:00.220Z","contentChangedAt":"2026-09-12T09:01:00.220Z","schemaVersion":2},"datasetVersion":"2026-09-19T12:17:13.211Z"}