json-path/JsonPath · error · InvalidPathException

Path must start with '$' or '@'

Error message

Path must start with '$' or '@'

What it means

The PathCompiler's readContextToken requires the very first token of a path to be '$' (root) or '@' (current/filter context). Any other starting character makes the path unparseable, so InvalidPathException is thrown during compilation.

Source

Thrown at json-path/src/main/java/com/jayway/jsonpath/internal/path/PathCompiler.java:107

            char c = path.currentChar();
            if (!isWhitespace(c)) {
                break;
            }
            path.incrementPosition(1);
        }
    }

    private Boolean isPathContext(char c) {
        return (c == DOC_CONTEXT || c == EVAL_CONTEXT);
    }

    //[$ | @]
    private RootPathToken readContextToken() {

        readWhitespace();

        if (!isPathContext(path.currentChar())) {
            throw new InvalidPathException("Path must start with '$' or '@'");
        }

        RootPathToken pathToken = PathTokenFactory.createRootPathToken(path.currentChar());

        if (path.currentIsTail()) {
            return pathToken;
        }

        path.incrementPosition(1);

        if(path.currentChar() != PERIOD && path.currentChar() != OPEN_SQUARE_BRACKET){
            fail("Illegal character at position " + path.position() + " expected '.' or '['");
        }

        PathTokenAppender appender = pathToken.getPathTokenAppender();
        readNextToken(appender);

        return pathToken;

View on GitHub (pinned to 62a4c9f0f6)

Solutions

  1. Prefix the path with `$` (absolute) or `@` (relative inside filters), e.g. `store.book` → `$.store.book`.
  2. Trim surrounding whitespace before compiling (leading whitespace is skipped, but content must start with $ or @).
  3. Validate user-supplied paths with a regex like `^[$@]` before passing to JsonPath.

Example fix

// before
JsonPath.read(json, "store.book[0].title");
// after
JsonPath.read(json, "$.store.book[0].title");
Defensive patterns

Strategy: validation

Validate before calling

boolean isWellFormedPathStart(String p) {
    String t = p == null ? "" : p.trim();
    return t.startsWith("$") || t.startsWith("@");
}

Try / catch

try {
    return JsonPath.compile(path);
} catch (InvalidPathException e) {
    throw new IllegalArgumentException("Path must start with $ or @: " + path, e);
}

Prevention

When it happens

Trigger: Passing paths like `store.book[0]`, `.foo`, or an empty/whitespace-only string to JsonPath.compile/read; paths that accidentally lost their leading `$` during string building or URL decoding.

Common situations: Building paths dynamically and forgetting the `$.` prefix; stripping `$` to 'normalize' then re-reading; receiving user-supplied path strings without validation.

Related errors


AI-assisted analysis of json-path/JsonPath@62a4c9f0f6 (2026-09-11). Data as JSON: /api/errors/c946320a340d2d39. Report an issue: GitHub.