json-path/JsonPath · error · JSONException

Invalid JSON

Error message

Invalid JSON

What it means

JettisonProvider.parse(JettisonTokener) peeks at the first non-whitespace character of the input and only accepts '{' (object) or '[' (array). Any other starting character — a bare string, number, 'true'/'false'/'null', or garbage — throws JSONException('Invalid JSON'). Note that jettison JSONException here is not caught by the enclosing catch of org.codehaus.jettison.json.JSONException unless it is that same class, in which case it becomes IllegalStateException; callers of parse(String) are declared to receive InvalidJsonException.

Source

Thrown at json-path/src/main/java/com/jayway/jsonpath/spi/json/JettisonProvider.java:202

		}
		
	}
	
	private Object parse(JettisonTokener JsonTokener)
	{
		try
		{
			char nextChar = JsonTokener.nextClean();
			JsonTokener.back();
			if (nextChar == '{') 
			{
				return new JettisonObject(JsonTokener);
			}
			if (nextChar == '[') 
			{
				return new JettisonArray(JsonTokener);
			}
			throw new JSONException("Invalid JSON");
		}
		catch( org.codehaus.jettison.json.JSONException jsonException )
		{
			throw new IllegalStateException(jsonException);
		}
	}
	
	@Override
	public Object parse(String json) throws InvalidJsonException 
	{
		return parse(new JettisonTokener(json));
	}
	
	@Override
	public Object parse(InputStream jsonStream, String charset) throws InvalidJsonException
	{
		try
		{

View on GitHub (pinned to 62a4c9f0f6)

Solutions

  1. Validate the payload starts with '{' or '[' before parsing: trim and check the first character, or attempt JSONValue validation
  2. If the API can return bare scalars, wrap them before parsing (e.g. serialize into an object) or use a different provider (JakartaJsonProvider/Jackson) that accepts scalar roots
  3. Catch InvalidJsonException (and IllegalStateException wrapping jettison JSONException) around JsonPath.parse and surface the raw payload for debugging
  4. Check HTTP response content-type and status before parsing to reject HTML/empty error bodies early

Example fix

// before
DocumentContext ctx = JsonPath.parse(responseBody); // body may be "42" or HTML
// after
String trimmed = responseBody == null ? "" : responseBody.trim();
if (trimmed.startsWith("{") || trimmed.startsWith("[")) {
    DocumentContext ctx = JsonPath.parse(trimmed);
} else {
    throw new InvalidJsonException("Expected JSON object/array, got: " + trimmed);
}
Defensive patterns

Strategy: validation

Validate before calling

// Java
static void requireJsonContainer(String body) {
    String t = body == null ? "" : body.trim();
    if (!(t.startsWith("{") || t.startsWith("[")))
        throw new InvalidJsonException("Not a JSON object/array: " + t.substring(0, Math.min(50, t.length())));
}

Type guard

boolean looksLikeJson(String body) {
    if (body == null) return false;
    String t = body.trim();
    return t.startsWith("{") || t.startsWith("[");
}

Try / catch

try {
    DocumentContext ctx = JsonPath.parse(body);
} catch (InvalidJsonException | IllegalStateException e) {
    // log raw payload, check content-type / HTTP status
}

Prevention

When it happens

Trigger: Calling JsonPath.parse(json) on a document that starts with anything other than '{' or '[' — e.g. a top-level scalar like '"hello"' or '42', an empty/blank string, HTML error pages, or truncated JSON whose first char is a stray token.

Common situations: APIs returning plain-text error pages (HTML '<html>...') with HTTP 200; services that return bare scalars which JSON-P-based providers accept but Jettison does not; empty response bodies from failed upstream calls; BOM or whitespace-only payloads where nextClean yields an unexpected char.

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 json-path/JsonPath@62a4c9f0f6 (2026-09-11). Data as JSON: /api/errors/29036ed0690e3a2b. Report an issue: GitHub.