How to Use JSON Path

https://bump.sh/blog/how-to-use-json-path

A few years ago most API designers, developers, and technical writers would have had very little reason to bump into JSONPath, but its starting to get more and more relevant as more tools and standards start relying on it. So what is JSONPath, what is it used for, and how can you get up to speed with using it?

JSONPath is a query language that can be used to extract data from JSON documents, which at first might not sound very exciting, but remember... OpenAPI is just a JSON (or YAML) document, so you can use JSONPath to poke around in OpenAPI and do various things.

You can use JSONPath for OpenAPI Overlays, to patch OpenAPI documents with extra documentation content, code samples, or whatever else.

You can use JSONPath in Spectral to write incredibly advanced linting rules which can power your automated API Style Guides.

You can even use JSONPath in AWS Step Functions.

JSONPath is popping up all over the the place these days, and if you work with OpenAPI it's definitely a handy tool to have on your belt.

How does JSONPath Work?

JSONPath is one of several query languages which will let you filter, query, and traverse through a chunk of JSON, not just to pull bits out, but to navigate complex data structures, with syntax for getting into specific array indexes, filtering through an objects properties or array values before continuing on to its children.

Here's a sample JSONPath from the RFC.

$.store.book[?@.price < 10].title

Anyone familiar with XPath in XML will be thinking "hmm, this looks pretty familiar!" and you're spot on, JSONPath is inspired by XPath. If you've never heard of XPath no worries, we'll start from scratch here.

To see how this works we'll need some JSON to run it against, so here is an example of some JSON from the RFC.

{
  "store": {
    "book": [
      {
        "category": "reference",
        "author": "Nigel Rees",
        "title": "Sayings of the Century",
        "price": 8.95
      },
      {
        "category": "fiction",
        "author": "Evelyn Waugh",
        "title": "Sword of Honour",
        "price": 12.99
      },
      {
        "category": "fiction",
        "author": "Herman Melville",
        "title": "Moby Dick",
        "isbn": "0-553-21311-3",
        "price": 8.99
      },
      {
        "category": "fiction",
        "author": "J. R. R. Tolkien",
        "title": "The Lord of the Rings",
        "isbn": "0-395-19395-8",
        "price": 22.99
      }
    ],
    "bicycle": {
      "color": "red",
      "price": 399
    }
  }
}

Now when you run that through any sort of JSONPath tool, you could expect to see these results.

[
  "Sayings of the Century",
  "Moby Dick"
]

Syntax

There is a whole lot of syntax to learn, but once you figure out the constituent pieces you can start to compile them into really advanced queries.

Syntax Element Description
$ root node identifier (Section 2.2)
@ current node identifier (Section 2.3.5) (valid only within filter selectors)
[<selectors>] child segment (Section 2.5.1): selects zero or more children of a node
.name shorthand for ['name' ]
.* shorthand for [*]
..⁠[<selectors>] descendant segment (Section 2.5.2): selects zero or more descendants of a node
..name shorthand for .. [' name' ]
..* shorthand for ..[*]
'name' name selector (Section 2.3.1): selects a named child of an object
* wildcard selector (Section 2.3.2): selects all children of a node
3 index selector (Section 2.3.3): selects an indexed child of an array (from 0)
0:100:5 array slice selector (Section 2.3.4): start:end:step for arrays
?<logical-expr> filter selector (Section 2.3.5): selects particular children using a logical expression
length(@.foo) function extension (Section 2.4): invokes a function in a filter expression

Overview of JSONPath Syntax, from RFC 9535.

Examples

If that isn't making too much sense, here are some examples to help you visualize.

JSONPath Intended Result
$.store.book[*].author the authors of all books in the store
$..author all authors
$.store.* all things in the store, which are some books and a red bicycle
$.store..price the prices of everything in the store
$..book[2] the third book
$..book[2].author the third book's author
$..book[2].publisher empty result: the third book does not have a "publisher" member
$..book[-1] the last book in order
$..book[0,1] the first two books
$..book[:2] the first two books
$..book[[email protected]] all books with an ISBN number
$..book[[email protected]<10] all books cheaper than 10
$..* all member values and array elements contained in the input value

Example JSONPath Expressions and Their Intended Results When Applied to the Example JSON Value, from RFC 9535: 1.5. JSONPath Examples.

By combining these bits of example syntax together you can do amazing and powerful things with JSONPath, so let's look at how to do those amazing things in OpenAPI.

JSONPath & OpenAPI

Take an OpenAPI document, like the Train Travel API.

git clone github.com/bump-sh-examples/train-travel-api
cd train-travel-api

Then install jsonpath-cli just so we can try some things out.

npm install -g @jsware/jsonpath-cli

Optional, if you're working with YAML, you might want to convert from YAML to JSON in the CLI too.

brew install yq
yq eval -o=json openapi.yaml > openapi.json

Don't worry this is just for playing around, all of the tooling that uses JSONPath will support YAML without bodges like this. Let's just get on the same page for this guide.

Querying OpenAPI with JSONPath

Once you have a JSON file to work with, we can use the jpp command, pass in a JSON/YAML document, and provide a JSONPath expression to query the document for specific parts.

$ jpp --pretty '$.info' openapi.json
[
  {
    "title": "Train Travel API",
    "description": "API for finding and booking train trips across Europe.",
    "version": "1.0.0",
    "contact": {
      "name": "Train Support",
      "url": "https://example.com/support",
      "email": "[email protected]"
    },
    "license": {
      "name": "Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International",
      "identifier": "CC-BY-NC-SA-4.0"
    }
  }
]

In this example $ refers to the root JSON document, then .info is using dot notation to access the info key in that object.

We can get a bit more advanced, and pull up a list of paths.

$ jpp --pretty '$.paths.*~' openapi.json
[
  "/stations",
  "/trips",
  "/bookings",
  "/bookings/{bookingId}",
  "/bookings/{bookingId}/payment"
]

This uses the .* syntax which is basically grabbing all children of the paths object, then using ~ to grab the keys instead of the values.

What sort of query language would JSONPath be if we could not do queries? Let's pull up a list of paths which are a get or a post, but ignore all the put, patch, delete, etc.

$ jpp --pretty '$.paths[?(@.put || @.post)]~' openapi.json
[
  "/bookings",
  "/bookings/{bookingId}/payment"
]

OpenAPI Overlays powered by JSONPath

One of the main uses for JSONPath will be for working OpenAPI documents, often by technical writers or other folks in the API governance space to check or improve OpenAPI documents.

Overlays are a list of actions, which make up a "target" which is a JSONPath, and an operation of either "update" or "remove".

Let's look at an update command.

# overlays.yaml
overlay: 1.0.0
info:
  title: Overlay to customise API for Protect Earth
  version: 0.0.1
actions:
  - target: '$.info'
    description: Update description and contact for our audience.
    update:
      description: >
        A new and much more interesting long form description, which has all sorts of
        Markdown, or more specifically [CommonMark](https://commonmark.org/) which
        is _like_ Markdown but **better**, because it's an actual standard instead of a
        series of sometimes vaguely consistent conventions.
        Anyway, this is a good place to write all sorts of helpful stuff, link to other
        getting started content, link to where people can find access tokens, or even
        paste some code samples for getting your first API request off the ground.
      contact:
        name: Support Team
        url: https://example.com/contact
        email: [email protected]

This overlays file is pointing to the JSONPath target $.info, then updating the object with the new bits of OpenAPI for description and contact, as per the OpenAPI specification. This can be handy for improving the quality of all sorts of descriptions, not just info, and for popping in support team contact information if the API developers inevitably forgot to mention that sort of thing.

Instead of using those yq or jpp tools we grabbed just to practice, we can use the Bump.sh CLI which has support for Overlays built in, and thankfully it'll work just fine with YAML or JSON.

npm install -g bump-cli
bump overlay openapi.yaml overlays.yaml > openapi.new.yaml

If we were to run that overlay on the Train Travel API, the resulting openapi.new.yaml would like like this:

openapi: 3.1.0
info:
  title: Train Travel API
  description: >
    A new and much more interesting long form description, which has all sorts
    of  Markdown, or more specifically [CommonMark](https://commonmark.org/)
    which  is _like_ Markdown but **better**, because its an actual standard
    instead of a  series of sometimes vaguely consistent conventions.
    Anyway, this is a good place to write all sorts of helpful stuff, link to
    other getting started content, link to where people can find access tokens,
    or even paste some code samples for getting your first API request off the
    ground.
  version: 1.0.0
  contact:
    name: Support Team
    url: 'https://example.com/contact'
    email: [email protected]
  license:
    name: Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International
    identifier: CC-BY-NC-SA-4.0
# snipped

When combined with more advanced queries you can start to get really specific with bits of the OpenAPI document you'd like to update, enabling all sorts of random use cases like cleaning up the servers list for publishing an API Catalogue, removing Development and Staging servers not accessible or relevant to API consumers.

# openapi.yaml
openapi: 3.1.0
servers:
  - url: http://localhost:3000
    description: Development
  - url: https://api-staging.example.com
    description: Staging
  - url: https://api.example.com
    description: Production

An overlay can target the servers array with $.servers then query through them with $.servers[?(@.description=="Development" || @.description=="Staging")], which is looking through objects in the array, and looking through the children for description: Development or description: Staging using basically JavaScript syntax.

The Overlay for this would combine that JSONPath target with remove: true operation like this:

# overlays.yaml
overlay: 1.0.0
info:
  title: Overlay to customise API
  version: 0.0.1
actions:
  - target: '$.servers[?(@.description=="Development" || @.description=="Staging")]'
    description: Remove Development and Staging servers but leave anything else.
    remove: true

That would leave this resulting OpenAPI.

# openapi.yaml
openapi: 3.1.0
servers:
  - url: https://api.example.com
    description: Production

Then the Developer Experience folks decide to roll out a Mocking or Sandbox experience, where consumers can play around with requests without actually triggering real emails, real data, or spending real money, but how can we show everyone where that is? Do we have to go and pester all the API teams to add it? Nope, just add another action.

# overlays.yaml
overlay: 1.0.0
info:
  title: Overlay to customise API
  version: 0.0.1
actions:
  - target: '$.servers[?(@.description=="Development" || @.description=="Staging")]'
    description: Remove Development and Staging servers but leave anything else.
    remove: true
  - target: '$.servers'
    description: Let everyone know about our amazing new hosted mocking/sandbox server.
    update:
      - description: Sandbox
        url: https://api-sandbox.example.com/

Leaning more about JSONPath

JSONPath made it to IETF "proposed standard" RFC status in 2024 (RFC 9535), but before then it was in a similar position to Markdown in the days before CommonMark, in that there are a few different variations of JSONPath as a concept.

  • JSONPath "The Blog Post" - Written by Stefan Gössner in 2007.
  • jsonpath.com - An online evaluator which as far as I can tell matches the blog post.
  • JSONPath-Plus - A popular (but now abandoned) fork which expands on the original specification to add some additional operators.
  • Nimma - A fork of JSONPath Plus created by the Stoplight team for Spectral to handle more advanced use cases. A list of caveats can be found here.

Then to further compound this confusion, all of the implementations have different support for certain features, and have filled in the grey areas differently due to their own interpretations and community requests. The amazing JSONPath Comparison project has collated all of the differences into a massive test suite and published the results, which was really helpful in shaping the new standard. Hopefully this will help tools converge, and we can forget all about this incompatibility.

For now, try to follow the RFC 9535 syntax, and use tooling which lines up with that syntax. Unfortunately that means not using jsonpath.com, and even the jpp CLI tool we used earlier is JSONPath Plus, which has a few differences to the RFC...

The Bump.sh CLI overlays functionality is JSONPath RFC 9535 compliant, and if you spot any valid RFC JSONPath syntax not working as expected please create an issue on GitHub so we can get that sorted out.

{
"by": "fmerian",
"descendants": 130,
"id": 40245637,
"kids": [
40246209,
40247663,
40245811,
40251934,
40251203,
40245757,
40246397,
40247260,
40246074,
40261754,
40249134,
40246457,
40253031,
40250784,
40247101,
40247741,
40246542,
40246503,
40249539,
40252121,
40245862,
40249122
],
"score": 255,
"time": 1714727188,
"title": "How to Use JSON Path",
"type": "story",
"url": "https://bump.sh/blog/how-to-use-json-path"
}
{
"author": null,
"date": "2024-04-30T00:00:00.000Z",
"description": "A few years ago most API designers, developers, and technical writers would have had very little reason to bump into JSONPath, but its starting to get more and more relevant as more tools and standards start relying on it. So what is JSONPath, what is it used for, and how can you get up to speed with using it?",
"image": "https://bump.sh/packs/static/how-to-json-path-6247a0101faaa9ba3ce4.png",
"logo": "https://logo.clearbit.com/bump.sh",
"publisher": "Bump.sh",
"title": "How to use JSON Path · Bump.sh",
"url": "https://bump.sh/blog/how-to-use-json-path"
}
{
"url": "https://bump.sh/blog/how-to-use-json-path",
"title": "How to use JSON Path · Bump.sh",
"description": "A few years ago most API designers, developers, and technical writers would have had very little reason to bump into JSONPath, but its starting to get more and more relevant as more tools and standards start relying on it. So what is JSONPath, what is it used for, and how can you get up to speed with using it?",
"links": [
"https://bump.sh/blog/how-to-use-json-path"
],
"image": "https://bump.sh/packs/static/how-to-json-path-6247a0101faaa9ba3ce4.png",
"content": "<div>\n<p>A few years ago most API designers, developers, and technical writers would have had very little reason to bump into JSONPath, but its starting to get more and more relevant as more tools and standards start relying on it. So what is JSONPath, what is it used for, and how can you get up to speed with using it?</p>\n<p>JSONPath is a query language that can be used to extract data from JSON documents, which at first might not sound very exciting, but remember... OpenAPI is just a JSON (or YAML) document, so you can use JSONPath to poke around in OpenAPI and do various things.</p>\n<p>You can use <a href=\"https://github.com/OAI/Overlay-Specification\" target=\"_blank\">JSONPath for OpenAPI Overlays</a>, to patch OpenAPI documents with extra documentation content, code samples, or whatever else.</p>\n<p>You can use <a href=\"https://docs.stoplight.io/docs/spectral/d3482ff0ccae9-rules#given\" target=\"_blank\">JSONPath in Spectral</a> to write incredibly advanced linting rules which can power your <a href=\"https://apisyouwonthate.com/blog/automated-style-guides-for-rest-graphql-grpc/\" target=\"_blank\">automated API Style Guides</a>.</p>\n<p>You can even use <a href=\"https://aws.amazon.com/blogs/compute/using-jsonpath-effectively-in-aws-step-functions/\" target=\"_blank\">JSONPath in AWS Step Functions</a>.</p>\n<p>JSONPath is popping up all over the the place these days, and if you work with OpenAPI it's definitely a handy tool to have on your belt.</p>\n<h2 id=\"how-does-jsonpath-work\">How does JSONPath Work?</h2>\n<p>JSONPath is one of several query languages which will let you filter, query, and traverse through a chunk of JSON, not just to pull bits out, but to navigate complex data structures, with syntax for getting into specific array indexes, filtering through an objects properties or array values before continuing on to its children.</p>\n<p>Here's a sample JSONPath from the RFC.</p>\n<div><pre><code><span>$</span><span>.</span><span>store</span><span>.</span><span>book</span><span>[?@.</span><span>price</span> <span>&lt;</span> <span>10</span><span>].</span><span>title</span>\n</code></pre></div><p>Anyone familiar with XPath in XML will be thinking \"hmm, this looks pretty familiar!\" and you're spot on, JSONPath is <a href=\"https://www.rfc-editor.org/rfc/rfc9535#inspired-by-xpath\" target=\"_blank\">inspired by XPath</a>. If you've never heard of XPath no worries, we'll start from scratch here.\n</p>\n<p>To see how this works we'll need some JSON to run it against, so here is an example of some JSON from the RFC.</p>\n<div><pre><code><span>{</span><span>\n </span><span>\"store\"</span><span>:</span><span> </span><span>{</span><span>\n </span><span>\"book\"</span><span>:</span><span> </span><span>[</span><span>\n </span><span>{</span><span>\n </span><span>\"category\"</span><span>:</span><span> </span><span>\"reference\"</span><span>,</span><span>\n </span><span>\"author\"</span><span>:</span><span> </span><span>\"Nigel Rees\"</span><span>,</span><span>\n </span><span>\"title\"</span><span>:</span><span> </span><span>\"Sayings of the Century\"</span><span>,</span><span>\n </span><span>\"price\"</span><span>:</span><span> </span><span>8.95</span><span>\n </span><span>},</span><span>\n </span><span>{</span><span>\n </span><span>\"category\"</span><span>:</span><span> </span><span>\"fiction\"</span><span>,</span><span>\n </span><span>\"author\"</span><span>:</span><span> </span><span>\"Evelyn Waugh\"</span><span>,</span><span>\n </span><span>\"title\"</span><span>:</span><span> </span><span>\"Sword of Honour\"</span><span>,</span><span>\n </span><span>\"price\"</span><span>:</span><span> </span><span>12.99</span><span>\n </span><span>},</span><span>\n </span><span>{</span><span>\n </span><span>\"category\"</span><span>:</span><span> </span><span>\"fiction\"</span><span>,</span><span>\n </span><span>\"author\"</span><span>:</span><span> </span><span>\"Herman Melville\"</span><span>,</span><span>\n </span><span>\"title\"</span><span>:</span><span> </span><span>\"Moby Dick\"</span><span>,</span><span>\n </span><span>\"isbn\"</span><span>:</span><span> </span><span>\"0-553-21311-3\"</span><span>,</span><span>\n </span><span>\"price\"</span><span>:</span><span> </span><span>8.99</span><span>\n </span><span>},</span><span>\n </span><span>{</span><span>\n </span><span>\"category\"</span><span>:</span><span> </span><span>\"fiction\"</span><span>,</span><span>\n </span><span>\"author\"</span><span>:</span><span> </span><span>\"J. R. R. Tolkien\"</span><span>,</span><span>\n </span><span>\"title\"</span><span>:</span><span> </span><span>\"The Lord of the Rings\"</span><span>,</span><span>\n </span><span>\"isbn\"</span><span>:</span><span> </span><span>\"0-395-19395-8\"</span><span>,</span><span>\n </span><span>\"price\"</span><span>:</span><span> </span><span>22.99</span><span>\n </span><span>}</span><span>\n </span><span>],</span><span>\n </span><span>\"bicycle\"</span><span>:</span><span> </span><span>{</span><span>\n </span><span>\"color\"</span><span>:</span><span> </span><span>\"red\"</span><span>,</span><span>\n </span><span>\"price\"</span><span>:</span><span> </span><span>399</span><span>\n </span><span>}</span><span>\n </span><span>}</span><span>\n</span><span>}</span><span>\n</span></code></pre></div>\n<p>Now when you run that through any sort of JSONPath tool, you could expect to see these results.</p>\n<div><pre><code><span>[</span><span>\n </span><span>\"Sayings of the Century\"</span><span>,</span><span>\n </span><span>\"Moby Dick\"</span><span>\n</span><span>]</span><span>\n</span></code></pre></div>\n<h3 id=\"syntax\">Syntax</h3>\n<p>There is a whole lot of syntax to learn, but once you figure out the constituent pieces you can start to compile them into really advanced queries.</p>\n<table><thead>\n<tr>\n<th>Syntax</th>\n<th>Element Description</th>\n</tr>\n</thead><tbody>\n<tr>\n<td><code>$</code></td>\n<td>root node identifier (Section 2.2)</td>\n</tr>\n<tr>\n<td><code>@</code></td>\n<td>current node identifier (Section 2.3.5) (valid only within filter selectors)</td>\n</tr>\n<tr>\n<td><code>[&lt;selectors&gt;]</code></td>\n<td>child segment (Section 2.5.1): selects zero or more children of a node</td>\n</tr>\n<tr>\n<td><code>.name</code></td>\n<td>shorthand for ['name' ]</td>\n</tr>\n<tr>\n<td><code>.*</code></td>\n<td>shorthand for [*]</td>\n</tr>\n<tr>\n<td><code>..⁠[&lt;selectors&gt;]</code></td>\n<td>descendant segment (Section 2.5.2): selects zero or more descendants of a node</td>\n</tr>\n<tr>\n<td><code>..name</code></td>\n<td>shorthand for .. [' name' ]</td>\n</tr>\n<tr>\n<td><code>..*</code></td>\n<td>shorthand for ..[*]</td>\n</tr>\n<tr>\n<td><code>'name'</code></td>\n<td>name selector (Section 2.3.1): selects a named child of an object</td>\n</tr>\n<tr>\n<td><code>*</code></td>\n<td>wildcard selector (Section 2.3.2): selects all children of a node</td>\n</tr>\n<tr>\n<td><code>3</code></td>\n<td>index selector (Section 2.3.3): selects an indexed child of an array (from 0)</td>\n</tr>\n<tr>\n<td><code>0:100:5</code></td>\n<td>array slice selector (Section 2.3.4): start:end:step for arrays</td>\n</tr>\n<tr>\n<td><code>?&lt;logical-expr&gt;</code></td>\n<td>filter selector (Section 2.3.5): selects particular children using a logical expression</td>\n</tr>\n<tr>\n<td><code>length(@.foo)</code></td>\n<td>function extension (Section 2.4): invokes a function in a filter expression</td>\n</tr>\n</tbody></table>\n<p><em>Overview of JSONPath Syntax, from <a href=\"https://www.rfc-editor.org/rfc/rfc9535#tbl-overview\" target=\"_blank\">RFC 9535</a>.</em></p>\n<h3 id=\"examples\">Examples</h3>\n<p>If that isn't making too much sense, here are some examples to help you visualize.</p>\n<table><thead>\n<tr>\n<th>JSONPath</th>\n<th>Intended Result</th>\n</tr>\n</thead><tbody>\n<tr>\n<td><code>$.store.book[*].author</code></td>\n<td>the authors of all books in the store</td>\n</tr>\n<tr>\n<td><code>$..author</code></td>\n<td>all authors</td>\n</tr>\n<tr>\n<td><code>$.store.*</code></td>\n<td>all things in the store, which are some books and a red bicycle</td>\n</tr>\n<tr>\n<td><code>$.store..price</code></td>\n<td>the prices of everything in the store</td>\n</tr>\n<tr>\n<td><code>$..book[2]</code></td>\n<td>the third book</td>\n</tr>\n<tr>\n<td><code>$..book[2].author</code></td>\n<td>the third book's author</td>\n</tr>\n<tr>\n<td><code>$..book[2].publisher</code></td>\n<td>empty result: the third book does not have a \"publisher\" member</td>\n</tr>\n<tr>\n<td><code>$..book[-1]</code></td>\n<td>the last book in order</td>\n</tr>\n<tr>\n<td><code>$..book[0,1]</code></td>\n<td>the first two books</td>\n</tr>\n<tr>\n<td><code>$..book[:2]</code></td>\n<td>the first two books</td>\n</tr>\n<tr>\n<td><code>$..book[[email protected]]</code></td>\n<td>all books with an ISBN number</td>\n</tr>\n<tr>\n<td><code>$..book[[email protected]&lt;10]</code></td>\n<td>all books cheaper than 10</td>\n</tr>\n<tr>\n<td><code>$..*</code></td>\n<td>all member values and array elements contained in the input value</td>\n</tr>\n</tbody></table>\n<p><em>Example JSONPath Expressions and Their Intended Results When Applied to the Example JSON Value, from <a href=\"https://www.rfc-editor.org/rfc/rfc9535#name-jsonpath-examples\" target=\"_blank\">RFC 9535: 1.5. JSONPath Examples</a>.</em></p>\n<p>By combining these bits of example syntax together you can do amazing and powerful things with JSONPath, so let's look at how to do those amazing things in OpenAPI.</p>\n<h3 id=\"jsonpath-openapi\">JSONPath &amp; OpenAPI</h3>\n<p>Take an OpenAPI document, like the <a href=\"https://github.com/bump-sh-examples/train-travel-api\" target=\"_blank\">Train Travel API</a>.</p>\n<div><pre><code>git clone github.com/bump-sh-examples/train-travel-api\n<span>cd </span>train-travel-api\n</code></pre></div>\n<p>Then install <a href=\"https://www.jsware.io/jsonpath-cli/\" target=\"_blank\">jsonpath-cli</a> just so we can try some things out.</p>\n<div><pre><code>npm <span>install</span> <span>-g</span> @jsware/jsonpath-cli\n</code></pre></div>\n<p>Optional, if you're working with YAML, you might want to convert from YAML to JSON in the CLI too.</p>\n<div><pre><code>brew <span>install </span>yq\nyq <span>eval</span> <span>-o</span><span>=</span>json openapi.yaml <span>&gt;</span> openapi.json\n</code></pre></div>\n<p>Don't worry this is just for playing around, all of the tooling that uses JSONPath will support YAML without bodges like this. Let's just get on the same page for this guide.</p>\n<h3 id=\"querying-openapi-with-jsonpath\">Querying OpenAPI with JSONPath</h3>\n<p>Once you have a JSON file to work with, we can use the <code>jpp</code> command, pass in a JSON/YAML document, and provide a JSONPath expression to query the document for specific parts.</p>\n<div><pre><code><span>$ </span>jpp <span>--pretty</span> <span>'$.info'</span> openapi.json\n<span>[</span>\n <span>{</span>\n <span>\"title\"</span>: <span>\"Train Travel API\"</span>,\n <span>\"description\"</span>: <span>\"API for finding and booking train trips across Europe.\"</span>,\n <span>\"version\"</span>: <span>\"1.0.0\"</span>,\n <span>\"contact\"</span>: <span>{</span>\n <span>\"name\"</span>: <span>\"Train Support\"</span>,\n <span>\"url\"</span>: <span>\"https://example.com/support\"</span>,\n <span>\"email\"</span>: <span>\"[email protected]\"</span>\n <span>}</span>,\n <span>\"license\"</span>: <span>{</span>\n <span>\"name\"</span>: <span>\"Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International\"</span>,\n <span>\"identifier\"</span>: <span>\"CC-BY-NC-SA-4.0\"</span>\n <span>}</span>\n <span>}</span>\n<span>]</span>\n</code></pre></div>\n<p>In this example <code>$</code> refers to the root JSON document, then <code>.info</code> is using dot notation to access the <code>info</code> key in that object.</p>\n<p>We can get a bit more advanced, and pull up a list of paths.</p>\n<div><pre><code><span>$ </span>jpp <span>--pretty</span> <span>'$.paths.*~'</span> openapi.json\n<span>[</span>\n <span>\"/stations\"</span>,\n <span>\"/trips\"</span>,\n <span>\"/bookings\"</span>,\n <span>\"/bookings/{bookingId}\"</span>,\n <span>\"/bookings/{bookingId}/payment\"</span>\n<span>]</span>\n</code></pre></div>\n<p>This uses the <code>.*</code> syntax which is basically grabbing all children of the paths object, then using <code>~</code> to grab the keys instead of the values.</p>\n<p>What sort of query language would JSONPath be if we could not do queries? Let's pull up a list of paths which are a <code>get</code> or a <code>post</code>, but ignore all the <code>put</code>, <code>patch</code>, <code>delete</code>, etc.</p>\n<div><pre><code><span>$ </span>jpp <span>--pretty</span> <span>'$.paths[?(@.put || @.post)]~'</span> openapi.json\n<span>[</span>\n <span>\"/bookings\"</span>,\n <span>\"/bookings/{bookingId}/payment\"</span>\n<span>]</span>\n</code></pre></div>\n<h2 id=\"openapi-overlays-powered-by-jsonpath\">OpenAPI Overlays powered by JSONPath</h2>\n<p>One of the main uses for JSONPath will be for working OpenAPI documents, often by technical writers or other folks in the API governance space to check or improve OpenAPI documents.</p>\n<p>Overlays are a list of actions, which make up a \"target\" which is a JSONPath, and an operation of either \"update\" or \"remove\".</p>\n<p>Let's look at an update command.</p>\n<div><pre><code><span># overlays.yaml</span>\n<span>overlay</span><span>:</span> <span>1.0.0</span>\n<span>info</span><span>:</span>\n <span>title</span><span>:</span> <span>Overlay to customise API for Protect Earth</span>\n <span>version</span><span>:</span> <span>0.0.1</span>\n<span>actions</span><span>:</span>\n <span>-</span> <span>target</span><span>:</span> <span>'</span><span>$.info'</span>\n <span>description</span><span>:</span> <span>Update description and contact for our audience.</span>\n <span>update</span><span>:</span>\n <span>description</span><span>:</span> <span>&gt;</span>\n <span>A new and much more interesting long form description, which has all sorts of</span>\n <span>Markdown, or more specifically [CommonMark](https://commonmark.org/) which</span>\n <span>is _like_ Markdown but **better**, because it's an actual standard instead of a</span>\n <span>series of sometimes vaguely consistent conventions.</span>\n <span>Anyway, this is a good place to write all sorts of helpful stuff, link to other</span>\n <span>getting started content, link to where people can find access tokens, or even</span>\n <span>paste some code samples for getting your first API request off the ground.</span>\n <span>contact</span><span>:</span>\n <span>name</span><span>:</span> <span>Support Team</span>\n <span>url</span><span>:</span> <span>https://example.com/contact</span>\n <span>email</span><span>:</span> <span>[email protected]</span>\n</code></pre></div>\n<p>This overlays file is pointing to the JSONPath target <code>$.info</code>, then updating the object with the new bits of OpenAPI for <code>description</code> and <code>contact</code>, as per the <a href=\"https://spec.openapis.org/oas/v3.1.0\" target=\"_blank\">OpenAPI specification</a>. This can be handy for improving the quality of all sorts of descriptions, not just info, and for popping in support team contact information if the API developers inevitably forgot to mention that sort of thing.</p>\n<p>Instead of using those <code>yq</code> or <code>jpp</code> tools we grabbed just to practice, we can use the <a href=\"https://github.com/bump-sh/cli\" target=\"_blank\">Bump.sh CLI</a> which has support for Overlays built in, and thankfully it'll work just fine with YAML or JSON.</p>\n<div><pre><code>npm <span>install</span> <span>-g</span> bump-cli\nbump overlay openapi.yaml overlays.yaml <span>&gt;</span> openapi.new.yaml\n</code></pre></div>\n<p>If we were to run that overlay on the Train Travel API, the resulting <code>openapi.new.yaml</code> would like like this:</p>\n<div><pre><code><span>openapi</span><span>:</span> <span>3.1.0</span>\n<span>info</span><span>:</span>\n <span>title</span><span>:</span> <span>Train Travel API</span>\n <span>description</span><span>:</span> <span>&gt;</span>\n <span>A new and much more interesting long form description, which has all sorts</span>\n <span>of Markdown, or more specifically [CommonMark](https://commonmark.org/)</span>\n <span>which is _like_ Markdown but **better**, because its an actual standard</span>\n <span>instead of a series of sometimes vaguely consistent conventions.</span>\n <span>Anyway, this is a good place to write all sorts of helpful stuff, link to</span>\n <span>other getting started content, link to where people can find access tokens,</span>\n <span>or even paste some code samples for getting your first API request off the</span>\n <span>ground.</span>\n <span>version</span><span>:</span> <span>1.0.0</span>\n <span>contact</span><span>:</span>\n <span>name</span><span>:</span> <span>Support Team</span>\n <span>url</span><span>:</span> <span>'</span><span>https://example.com/contact'</span>\n <span>email</span><span>:</span> <span>[email protected]</span>\n <span>license</span><span>:</span>\n <span>name</span><span>:</span> <span>Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International</span>\n <span>identifier</span><span>:</span> <span>CC-BY-NC-SA-4.0</span>\n<span># snipped</span>\n</code></pre></div>\n<p>When combined with more advanced queries you can start to get really specific with bits of the OpenAPI document you'd like to update, enabling all sorts of random use cases like cleaning up the servers list for publishing an API Catalogue, removing Development and Staging servers not accessible or relevant to API consumers.</p>\n<div><pre><code><span># openapi.yaml</span>\n<span>openapi</span><span>:</span> <span>3.1.0</span>\n<span>servers</span><span>:</span>\n <span>-</span> <span>url</span><span>:</span> <span>http://localhost:3000</span>\n <span>description</span><span>:</span> <span>Development</span>\n <span>-</span> <span>url</span><span>:</span> <span>https://api-staging.example.com</span>\n <span>description</span><span>:</span> <span>Staging</span>\n <span>-</span> <span>url</span><span>:</span> <span>https://api.example.com</span>\n <span>description</span><span>:</span> <span>Production</span>\n</code></pre></div>\n<p>An overlay can target the servers array with <code>$.servers</code> then query through them with <code>$.servers[?(@.description==\"Development\" || @.description==\"Staging\")]</code>, which is looking through objects in the array, and looking through the children for <code>description: Development</code> or <code>description: Staging</code> using basically JavaScript syntax.</p>\n<p>The Overlay for this would combine that JSONPath target with <code>remove: true</code> operation like this:</p>\n<div><pre><code><span># overlays.yaml</span>\n<span>overlay</span><span>:</span> <span>1.0.0</span>\n<span>info</span><span>:</span>\n <span>title</span><span>:</span> <span>Overlay to customise API</span>\n <span>version</span><span>:</span> <span>0.0.1</span>\n<span>actions</span><span>:</span>\n <span>-</span> <span>target</span><span>:</span> <span>'</span><span>$.servers[?(@.description==\"Development\"</span><span> </span><span>||</span><span> </span><span>@.description==\"Staging\")]'</span>\n <span>description</span><span>:</span> <span>Remove Development and Staging servers but leave anything else.</span>\n <span>remove</span><span>:</span> <span>true</span>\n</code></pre></div>\n<p>That would leave this resulting OpenAPI.</p>\n<div><pre><code><span># openapi.yaml</span>\n<span>openapi</span><span>:</span> <span>3.1.0</span>\n<span>servers</span><span>:</span>\n <span>-</span> <span>url</span><span>:</span> <span>https://api.example.com</span>\n <span>description</span><span>:</span> <span>Production</span>\n</code></pre></div>\n<p>Then the Developer Experience folks decide to roll out a Mocking or Sandbox experience, where consumers can play around with requests without actually triggering real emails, real data, or spending real money, but how can we show everyone where that is? Do we have to go and pester all the API teams to add it? Nope, just add another action.</p>\n<div><pre><code><span># overlays.yaml</span>\n<span>overlay</span><span>:</span> <span>1.0.0</span>\n<span>info</span><span>:</span>\n <span>title</span><span>:</span> <span>Overlay to customise API</span>\n <span>version</span><span>:</span> <span>0.0.1</span>\n<span>actions</span><span>:</span>\n <span>-</span> <span>target</span><span>:</span> <span>'</span><span>$.servers[?(@.description==\"Development\"</span><span> </span><span>||</span><span> </span><span>@.description==\"Staging\")]'</span>\n <span>description</span><span>:</span> <span>Remove Development and Staging servers but leave anything else.</span>\n <span>remove</span><span>:</span> <span>true</span>\n <span>-</span> <span>target</span><span>:</span> <span>'</span><span>$.servers'</span>\n <span>description</span><span>:</span> <span>Let everyone know about our amazing new hosted mocking/sandbox server.</span>\n <span>update</span><span>:</span>\n <span>-</span> <span>description</span><span>:</span> <span>Sandbox</span>\n <span>url</span><span>:</span> <span>https://api-sandbox.example.com/</span>\n</code></pre></div>\n<h3 id=\"leaning-more-about-jsonpath\">Leaning more about JSONPath</h3>\n<p>JSONPath made it to IETF \"proposed standard\" RFC status in 2024 (<a href=\"https://www.rfc-editor.org/rfc/rfc9535\" target=\"_blank\">RFC 9535</a>), but before then it was in a similar position to <a href=\"https://philsturgeon.com/state-of-markdown/\" target=\"_blank\">Markdown in the days before CommonMark</a>, in that there are a few different variations of JSONPath as a concept.</p>\n<ul>\n<li><a href=\"https://goessner.net/articles/JsonPath/\" target=\"_blank\">JSONPath \"The Blog Post\"</a> - Written by Stefan Gössner in 2007.</li>\n<li><a href=\"https://jsonpath.com/\" target=\"_blank\">jsonpath.com</a> - An online evaluator which as far as I can tell matches the blog post.</li>\n<li><a href=\"https://www.npmjs.com/package/jsonpath-plus\" target=\"_blank\">JSONPath-Plus</a> - A popular (but now abandoned) fork which expands on the original specification to add some additional operators.</li>\n<li><a href=\"https://www.npmjs.com/package/nimma\" target=\"_blank\">Nimma</a> - A fork of JSONPath Plus created by the Stoplight team for Spectral to handle more advanced use cases. A list of caveats can be found here.</li>\n</ul>\n<p>Then to further compound this confusion, all of the implementations have different support for certain features, and have filled in the grey areas differently due to their own interpretations and community requests. The amazing <a href=\"https://cburgmer.github.io/json-path-comparison/\" target=\"_blank\">JSONPath Comparison project</a> has collated all of the differences into a massive test suite and published the results, which was really helpful in shaping the new standard. Hopefully this will help tools converge, and we can forget all about this incompatibility.</p>\n<p>For now, try to follow the RFC 9535 syntax, and use tooling which lines up with that syntax. Unfortunately that means not using <code>jsonpath.com</code>, and even the <code>jpp</code> CLI tool we used earlier is JSONPath Plus, which has a few differences to the RFC...</p>\n<p>The Bump.sh CLI <code>overlays</code> functionality is JSONPath RFC 9535 compliant, and if you spot any valid RFC JSONPath syntax not working as expected please <a href=\"https://github.com/bump-sh/cli/issues\" target=\"_blank\">create an issue on GitHub</a> so we can get that sorted out.</p>\n </div>",
"author": "@bump_hq",
"favicon": "https://bump.sh/favicon.svg",
"source": "bump.sh",
"published": "",
"ttr": 406,
"type": "article"
}