karatelabs/karate · error
Unexpected token ' ' in JSON
Error message
Unexpected token '${c}' in JSON What it means
The JSON parser encountered a character that cannot start a JSON value where one was required. After switching on `{`, `[`, `"`, and literal starts, the default branch allows only `-` or digits for numbers; anything else triggers "Unexpected token '<c>' in JSON". This mirrors JSON.parse's own error style.
Solutions
- Quote strings with double quotes and use only JSON literals (null, true, false, numbers) in the input.
- Strip any non-JSON prefix/suffix (e.g. HTML, BOM, log lines) before parsing.
- Validate the payload with a linter or JSON.parse in a test to confirm it is strict JSON.
Example fix
// before
JSON.parse("{'name': 'a'}");
// after
JSON.parse('{"name": "a"}'); Defensive patterns
Strategy: validation
Validate before calling
// cheap pre-check for obviously non-JSON starts
var t = input.trim();
if (!(t.startsWith('{') || t.startsWith('[') || t.startsWith('"') || /^-?[0-9tfn]/.test(t))) {
throw new IllegalArgumentException('input does not look like JSON: ' + t.substring(0, 20));
} Try / catch
try {
var obj = JSON.parse(input);
} catch (e) {
if (('' + e).indexOf('Unexpected token') >= 0) {
console.log('non-JSON content near start of: ' + input.substring(0, 40));
}
throw e;
} Prevention
- Use strict JSON syntax: double quotes, no undefined/NaN/single quotes.
- Strip HTML error pages or BOM before parsing response bodies.
- Round-trip generated JSON through a serializer in tests.
When it happens
Trigger: Parsing input like `"undefined"`, `"{'a':1}"` (single quotes), `"NaN"`, or stray text before/after a JSON document, where the offending character reaches parseValue's default branch.
Common situations: Passing JS literals (undefined, NaN, single-quoted objects) where strict JSON is required; response bodies that contain HTML error pages; copy-pasted JSON with smart quotes or BOM/leading garbage.
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.
- Parsing and encoding errors: unexpected token, malformed input — why parsers reject input and how to find the real culprit.
Related errors
- Expected string key in object
- Expected ':' after object key
- Unexpected end of JSON input in object
- Unexpected end of JSON input in array
- Invalid number: bare '-'
AI-assisted analysis of karatelabs/karate@a22eb90246 (2026-09-12).
Data as JSON: /api/errors/f00acf7a343cbdbc.
Report an issue: GitHub.
Appendix: source
Thrown at karate-js/src/main/java/io/karatelabs/js/JsonParser.java:99
}
char c = s.charAt(pos);
switch (c) {
case '{':
return parseObject();
case '[':
return parseArray();
case '"':
return parseString();
case 't':
case 'f':
return parseBoolean();
case 'n':
return parseNull();
default:
if (c == '-' || (c >= '0' && c <= '9')) {
return parseNumber();
}
throw syntaxError("Unexpected token '" + c + "' in JSON");
}
}
private Map<String, Object> parseObject() {
// we know s.charAt(pos) == '{'
pos++;
Map<String, Object> map = new LinkedHashMap<>();
skipWs();
if (pos < len && s.charAt(pos) == '}') {
pos++;
return map;
}
while (true) {
skipWs();
if (pos >= len || s.charAt(pos) != '"') {
throw syntaxError("Expected string key in object");
}
String key = parseString();View on GitHub (pinned to a22eb90246)