JSONPath

JSONPath is a query language for JSON, similar to how XPath works for XML. It lets you extract specific values from a JSON document without parsing the entire structure manually. JSONPath expressions are short, readable, and powerful — especially when working with large, deeply nested JSON data.

What Problem Does JSONPath Solve

Imagine a large JSON response from a weather API containing hundreds of fields. You only need the temperature for today. Without JSONPath, you write nested code like data.forecast.daily[0].temperature.value. With JSONPath, you write a single expression that fetches exactly what you need — and it works even if the structure changes slightly.

Think of JSONPath like GPS for your JSON. Instead of manually navigating every street to reach a destination, you provide an address and the GPS finds the route for you.

JSONPath Syntax Basics

Root Selector: $

Every JSONPath expression starts with $. This represents the root of the JSON document, like the top-level object or array.

Dot Notation: .key

Use a dot followed by a key name to go one level deeper.

Bracket Notation: ["key"] or [index]

Use brackets to access keys with special characters or array elements by index.

Wildcard: *

The asterisk matches all elements or all keys at that level.

Recursive Descent: ..

Two dots search all levels of the JSON, no matter how deep.

Filter Expression: [?()]

Use filter expressions to select elements based on conditions.

Sample JSON for Examples

{
  "store": {
    "name": "BookWorld",
    "location": "Mumbai",
    "books": [
      {
        "title": "Clean Code",
        "author": "Robert Martin",
        "price": 499,
        "category": "programming",
        "inStock": true
      },
      {
        "title": "Atomic Habits",
        "author": "James Clear",
        "price": 350,
        "category": "self-help",
        "inStock": true
      },
      {
        "title": "Dune",
        "author": "Frank Herbert",
        "price": 620,
        "category": "fiction",
        "inStock": false
      }
    ],
    "manager": {
      "name": "Pooja Iyer",
      "email": "pooja@bookworld.com"
    }
  }
}

JSONPath Expression Examples

Get the Store Name

$.store.name

Result: "BookWorld"

Get All Books

$.store.books

Result: The entire books array with all three objects.

Get the First Book

$.store.books[0]

Result: The first book object (Clean Code).

Get the Title of the Second Book

$.store.books[1].title

Result: "Atomic Habits"

Get All Book Titles

$.store.books[*].title

Result: ["Clean Code", "Atomic Habits", "Dune"]

Get All Prices Anywhere in the Document

$..price

Result: [499, 350, 620] — The recursive descent .. searches every level.

Get All Titles Anywhere in the Document

$..title

Result: ["Clean Code", "Atomic Habits", "Dune"]

Filter Expressions

Filter expressions let you query based on conditions. The syntax is [?(@.key operator value)] where @ refers to the current element.

Get Books That Are In Stock

$.store.books[?(@.inStock == true)]

Result: Clean Code and Atomic Habits objects (both have inStock: true).

Get Books Cheaper Than 500

$.store.books[?(@.price < 500)]

Result: Clean Code (499) and Atomic Habits (350).

Get Books in the Programming Category

$.store.books[?(@.category == "programming")]

Result: The Clean Code object.

Diagram: JSONPath Navigation

$ (root)
└── store
    ├── name          <-- $.store.name
    ├── location      <-- $.store.location
    ├── books[]       <-- $.store.books
    │   ├── [0]       <-- $.store.books[0]
    │   │   ├── title <-- $.store.books[0].title
    │   │   └── price <-- $.store.books[0].price
    │   ├── [1]
    │   └── [2]
    └── manager
        └── name      <-- $.store.manager.name

Array Slicing

JSONPath supports array slicing similar to Python. The syntax is [start:end:step].

Get the First Two Books

$.store.books[0:2]

Result: Books at index 0 and 1 (Clean Code and Atomic Habits).

Get the Last Book

$.store.books[-1]

Result: Dune (the last item).

Using JSONPath in JavaScript

JavaScript does not have native JSONPath support. Use the jsonpath npm package.

Install the Package

npm install jsonpath

Use JSONPath in Code

const jp = require('jsonpath');
const data = require('./store.json');

// Get all book titles
const titles = jp.query(data, '$.store.books[*].title');
console.log(titles);
// ["Clean Code", "Atomic Habits", "Dune"]

// Get books cheaper than 500
const cheapBooks = jp.query(data, '$.store.books[?(@.price < 500)]');
console.log(cheapBooks);

Using JSONPath in Python

Install the jsonpath-ng library:

pip install jsonpath-ng
import json
from jsonpath_ng import parse

with open('store.json') as f:
    data = json.load(f)

# Get all book titles
expression = parse('$.store.books[*].title')
titles = [match.value for match in expression.find(data)]
print(titles)
# ['Clean Code', 'Atomic Habits', 'Dune']

Online JSONPath Testers

You can test JSONPath expressions without writing any code:

  • JSONPath Online Evaluator at jsonpath.com
  • JSONPath Finder in browser dev tools
  • Postman's JSONPath expressions in test scripts

JSONPath in API Testing with Postman

Postman supports JSONPath in test scripts to validate API responses.

// In Postman Test Script
const response = pm.response.json();
const titles = response.store.books.map(b => b.title);
pm.test("First book is Clean Code", () => {
    pm.expect(titles[0]).to.equal("Clean Code");
});

Some test frameworks also support direct JSONPath assertions in their syntax.

Common JSONPath Operators Reference

Expression      Meaning
----------      -------
$               Root element
.key            Child key using dot notation
["key"]         Child key using bracket notation
[n]             Array element at index n
[*]             All array elements
..key           Recursive search for key
[start:end]     Array slice
[?(condition)]  Filter based on condition
@               Current element (inside filter)

JSONPath vs JavaScript Dot Notation

JSONPath                              JavaScript
-------                              ----------
$.store.name                         data.store.name
$.store.books[0].title               data.store.books[0].title
$.store.books[*].title               data.store.books.map(b => b.title)
$.store.books[?(@.price < 500)]      data.store.books.filter(b => b.price < 500)
$..price                             (requires recursive function in JS)

When to Use JSONPath

  • Extracting specific values from large API responses.
  • Writing assertions in API test frameworks.
  • Processing deeply nested JSON without writing loops.
  • Selecting data in tools like Postman, AWS Step Functions, or Elasticsearch.

Summary

JSONPath is a query language that lets you pinpoint exactly what you need inside a JSON document. Use $ as the root, dots to navigate, brackets for arrays, wildcards for bulk selection, and filter expressions for conditional queries. JSONPath is available in JavaScript and Python through libraries and is widely supported in API testing tools like Postman.

Leave a Comment

Your email address will not be published. Required fields are marked *