liveBook · Manning

JSON path language

As explained in The Design of Web APIs, Second Edition

JSONPath is a query language and expression syntax for selecting and extracting values from JSON-like hierarchical data.

JSONPath selects values within a JSON or YAML document. In API linting, a Spectral rule puts one or more JSONPath expressions in `given` to find OpenAPI elements; its `then` checks the values found. A rule can therefore target the API version, parameter names, operations, or responses without checking every element. section 18.3.2 section 18.5

Start with the smallest expression that selects the elements you need:

  • `$` is the document root, and `$.info.version` selects the version property of the root `info` object. section 18.5.1
  • `*` selects an object's values or an array's items; `$.paths.*[post,put].responses` selects response objects for POST and PUT operations. section 18.5.2
  • `..` searches through the document, while `[?(conditions)]` filters matches. `$..parameters[?(@.in === "query" || @.in === "path")]` selects query and path parameters. section 18.5.2

Check query-parameter naming

Set a rule's `given` to `$..parameters[?(@.in === "query")].name`, then apply Spectral's `casing` function with the `camel` option. A query parameter named `buyPRice` is reported because its name is not camel-cased. section 18.3.2

Test a new selector before adding its real check: temporarily use Spectral's `undefined` function in `then` and lint a valid, realistic OpenAPI document. The reported locations reveal what `given` found. Prefer several clear paths over one complex path when possible; a broad recursive search can also select unintended schema properties. section 18.5.1 section 18.5.2

For Spectral rules, consult JSONPath Plus documentation when an expression's behavior matters: Spectral uses that implementation, which includes features beyond standardized JSONPath. section 18.5

How The Design of Web APIs, Second Edition covers it

How deep it goes
Works through root selection, wildcards, recursive search, key alternatives, filters, and selector testing; defers implementation-specific details to JSONPath Plus documentation.
Examples
Uses API versions, query-parameter names, POST and PUT responses, and query or path parameters as selection targets.
What it assumes
Assumes JSON or YAML document structure while introducing selection from the root before broader searches and filters.
What you can do after
Apply it via Spectral to target lint checks and verify selected locations with a temporary `undefined` check.
How it connects
Connects JSONPath to Spectral rules, OpenAPI documents, API linting, and reusable rule aliases.

Also explained in

Compare how 3 books explain JSON path language →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Design of Web APIs, Second Edition. The section links point to the parts of the book it draws on.