Skip to the content
GigaJSON
All tools
Format and check
View and query
Convert
JSON to code
Encode and decode
Sample files
Guides Open GigaJSON

How to find the path to a value in JSON

· 5 min read · By Amir Badi

You can see the value you need in an API response, but the code, the query or the n8n node wants its path: orders[0].items[1].sku, written in the right syntax. Counting brackets by hand works for small documents and goes wrong on deep ones. This guide shows how to read a path, how each language writes it, and how to find it by clicking or with jq, Python and JavaScript.

Every example uses this shop.json, and every output below is what jq 1.7, Python 3.12, Node 24, jsonpath-plus and jmespath.js actually printed:

{
  "store": "north",
  "orders": [
    {
      "id": "A-100",
      "customer": { "name": "Ana", "email": "ana@example.com" },
      "items": [ { "sku": "KB-01", "qty": 1 }, { "sku": "MS-02", "qty": 2 } ]
    },
    {
      "id": "A-101",
      "customer": { "name": "Ben", "email": "ben@example.com" },
      "items": [ { "sku": "KB-01", "qty": 3 } ]
    }
  ],
  "settings": { "ship to": "EU" }
}

Reading a path

A path is the list of steps from the top of the document to one value. To reach "MS-02": open orders, take the first order (index 0, since lists count from zero), open items, take the second item (index 1), read sku. As a list of steps that is ["orders", 0, "items", 1, "sku"]: keys are text, list positions are numbers.

The same path in each language

Language Path to "MS-02" Path to "EU" (key with a space)
JSONPath $.orders[0].items[1].sku $.settings['ship to']
jq .orders[0].items[1].sku .settings["ship to"]
JMESPath orders[0].items[1].sku settings."ship to"
JavaScript data.orders[0].items[1].sku data.settings["ship to"]
Python data["orders"][0]["items"][1]["sku"] data["settings"]["ship to"]
JSON Pointer /orders/0/items/1/sku /settings/ship to

Two differences cause most mistakes. JSONPath starts with $ and jq with ., while JMESPath starts with neither. And a key that isn't a plain word (a space, a dot, a dash, or a leading digit) needs quotes and brackets in every language except JSON Pointer, which uses ~0 for ~ and ~1 for / instead.

To get every SKU instead of one, replace the index with a wildcard: $.orders[*].items[*].sku in JSONPath, .orders[].items[].sku in jq, orders[].items[].sku in JMESPath. All three return ["KB-01", "MS-02", "KB-01"] (jq without -c prints them one per line). JSONPath's $..sku finds sku at any depth. A JSON Pointer has no wildcard.

By clicking

The JSON Path Finder does this for you. Paste the JSON or open a file, then click a line of the text or a node in the tree. It writes the path in ten forms (JSONPath, jq, JMESPath, JavaScript, Python, JSON Pointer, n8n, Postman, PowerShell and PHP), quoting odd keys the way each language expects. On a value inside a list, All items turns the index into a wildcard and lists the values it matches. To find a value you can't see, type part of it in the search box; to check where a path you already have points, paste the path there.

Browsers can do a little of this too. In Chrome's DevTools console, expand an object, right-click a property and choose Copy property path. VS Code shows the path to the cursor in the breadcrumbs bar above a JSON file.

With jq

jq's paths(f) lists the path of every value for which f is true:

jq -c 'paths(. == "MS-02")' shop.json
["orders",0,"items",1,"sku"]

A value that appears more than once gives one path per match:

jq -c 'paths(. == "KB-01")' shop.json
["orders",0,"items",0,"sku"]
["orders",1,"items",0,"sku"]

To find a key instead of a value, test the last step of each path:

jq -c 'paths | select(.[-1] == "email")' shop.json
["orders",0,"customer","email"]
["orders",1,"customer","email"]

The test can be any jq expression, such as every string ending in @example.com:

jq -c 'paths(type == "string" and test("@example\\.com$"))' shop.json

paths(scalars) lists the path of every leaf (string, number, boolean or null), which is a quick way to see the whole shape of an unfamiliar file.

A path array goes straight back into jq with getpath:

jq 'getpath(["orders",0,"items",1,"sku"])' shop.json     # "MS-02"

To turn it into text you can paste into a jq filter, or into a JSON Pointer:

jq -r 'paths(. == "MS-02") | map(if type == "number" then "[\(.)]" else ".\(.)" end) | join("")' shop.json
# .orders[0].items[1].sku

jq -r 'paths(. == "MS-02") | "/" + (map(tostring | gsub("~"; "~0") | gsub("/"; "~1")) | join("/"))' shop.json
# /orders/0/items/1/sku

The first one writes keys as .name, so it breaks on keys with spaces or dots. For those, the path finder's quoting is safer.

In Python

A small recursive function walks the document and yields the path of every match:

import json

def find_paths(node, match, path=()):
    """Yield the path (a tuple of keys and indexes) of every value where match(value) is true."""
    if match(node):
        yield path
    if isinstance(node, dict):
        for key, value in node.items():
            yield from find_paths(value, match, path + (key,))
    elif isinstance(node, list):
        for i, value in enumerate(node):
            yield from find_paths(value, match, path + (i,))

with open("shop.json", encoding="utf-8") as f:
    data = json.load(f)

for p in find_paths(data, lambda v: v == "KB-01"):
    print(p)
('orders', 0, 'items', 0, 'sku')
('orders', 1, 'items', 0, 'sku')

match gets every value, objects and lists included, so the test can be anything: lambda v: isinstance(v, str) and v.endswith("@example.com"), for example.

In JavaScript

The same idea as a generator, for Node or the browser console:

function* findPaths(node, match, path = []) {
  if (match(node)) yield path;
  if (node && typeof node === 'object')
    for (const [key, value] of Object.entries(node))
      yield* findPaths(value, match, [...path, Array.isArray(node) ? Number(key) : key]);
}

for (const p of findPaths(data, v => v === 'KB-01')) console.log(JSON.stringify(p));
// ["orders",0,"items",0,"sku"]
// ["orders",1,"items",0,"sku"]

If the project already uses jsonpath-plus, it can return paths instead of values:

JSONPath({ path: '$..[?(@ === "KB-01")]', json: data, resultType: 'path' });
// [ "$['orders'][0]['items'][0]['sku']", "$['orders'][1]['items'][0]['sku']" ]

Check the path before you rely on it

A path that's off by one index still returns a value, just the wrong one. Run it against the real document before it goes into code: the JSONPath Tester, the jq Playground and the JMESPath Playground each show what a path matches. jq vs JSONPath vs JMESPath compares the three languages task by task, and JSONPath examples covers JSONPath in JavaScript, Python, PostgreSQL and kubectl.

For a big file, open it in the GigaJSON app: select a node in the tree and the path bar above shows its path, at any depth and in files up to 1 GB.

Questions

How do I find the path to a value in JSON?

Paste the JSON into a path finder and click the value; it writes the path for you, such as $.orders[0].items[1].sku. In code, search the document: jq -c 'paths(. == "MS-02")' file.json prints the path as a list of keys and indexes, and a short recursive function does the same in Python or JavaScript.

What does a JSON path look like?

The keys and list positions from the top of the document to the value. The same path is written $.orders[0].sku in JSONPath, .orders[0].sku in jq, orders[0].sku in JMESPath, data.orders[0].sku in JavaScript, data["orders"][0]["sku"] in Python and /orders/0/sku as a JSON Pointer.

How do I find every path to a key with jq?

Use paths and test the last element: jq -c 'paths | select(.[-1] == "email")' file.json lists every path that ends in an email key, wherever it sits in the document.

How do I write a path to a key with a space or a dot in it?

Put it in brackets with quotes: $['ship to'] in JSONPath, .["ship to"] in jq, "ship to" in double quotes in JMESPath, and data["ship to"] in JavaScript and Python. Without the quotes, the space or dot is read as part of the syntax.

What is the difference between a JSON path and a JSON Pointer?

A JSON Pointer (RFC 6901) always points at exactly one value, written with slashes: /orders/0/sku. JSON Patch, JSON Schema and OpenAPI use it. JSONPath (RFC 9535) is a query language whose paths can also match many values, like $.orders[*].sku.

More from the blog