惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Engineering at Meta
Engineering at Meta
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
腾讯CDC
宝玉的分享
宝玉的分享
量子位
Recent Announcements
Recent Announcements
Martin Fowler
Martin Fowler
J
Java Code Geeks
V
Visual Studio Blog
阮一峰的网络日志
阮一峰的网络日志
Blog — PlanetScale
Blog — PlanetScale
大猫的无限游戏
大猫的无限游戏
博客园 - 叶小钗
S
SegmentFault 最新的问题
B
Blog
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
博客园 - 【当耐特】
小众软件
小众软件
The Cloudflare Blog
Y
Y Combinator Blog
I
InfoQ
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
GbyAI
GbyAI
IT之家
IT之家

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
How to Query Nested JSON with JSONPath (Without Writing L...
Tahmid · 2026-05-03 · via DEV Community

You just got back a 300-line API response. Somewhere inside three levels of nesting is the email field you actually need. So you write a loop, then another loop, then a conditional — and now you're maintaining brittle traversal code that breaks every time the API schema shifts.

There's a better way: JSONPath.

JSONPath is a query language for JSON, similar to how XPath works for XML. Instead of writing code to traverse a structure, you write a short expression that reads like a path. It works across languages, and once you learn the syntax, you'll reach for it constantly.

The Basics: What JSONPath Looks Like

Here's a typical API response — a list of orders, each with nested customer and item data:

{
  "store": {
    "orders": [
      {
        "id": 1,
        "customer": { "name": "Alice", "email": "alice@example.com" },
        "items": [{"sku": "A1", "qty": 2}, {"sku": "B3", "qty": 1}]
      },
      {
        "id": 2,
        "customer": { "name": "Bob", "email": "bob@example.com" },
        "items": [{"sku": "C7", "qty": 5}]
      }
    ]
  }
}

Enter fullscreen mode Exit fullscreen mode

To get every customer email without writing any loops:

$.store.orders[*].customer.email

Enter fullscreen mode Exit fullscreen mode

Result:

["alice@example.com", "bob@example.com"]

Enter fullscreen mode Exit fullscreen mode

The $ represents the root. The . navigates into an object key. [*] means "all array elements." Three characters replace a full nested loop.

Filtering: The Real Power

JSONPath shines when you need to filter by a condition. Say you only want items where qty is greater than 1:

$.store.orders[*].items[?(@.qty > 1)]

Enter fullscreen mode Exit fullscreen mode

Result:

[
  {"sku": "A1", "qty": 2},
  {"sku": "C7", "qty": 5}
]

Enter fullscreen mode Exit fullscreen mode

The ?() is a filter expression. @ refers to the current node. You can combine conditions with && and ||, check for key existence with @.key, and do string comparisons too.

Here's the equivalent Python — same outcome, but compare the cognitive load:

# Without JSONPath — five lines, easy to get wrong
results = []
for order in data["store"]["orders"]:
    for item in order["items"]:
        if item["qty"] > 1:
            results.append(item)

Enter fullscreen mode Exit fullscreen mode

The JSONPath version is one line and self-documenting. Anyone reading it immediately knows what data you're after.

Recursive Descent: Finding a Key Anywhere in the Tree

Sometimes you don't know exactly where a key lives — you just know it exists somewhere in a deeply nested structure. The .. (recursive descent) operator handles this:

$..email

Enter fullscreen mode Exit fullscreen mode

This finds every email field at any depth in the document. It's invaluable for exploring unfamiliar API schemas or debugging payloads where nesting is inconsistent across records.

Try it live with the JSONPath Evaluator on jsonindenter.com — paste your JSON, type any expression, and see matched results highlighted instantly. No installation, nothing leaves your browser.

A Practical Workflow for Real API Responses

When you're dealing with a large, unfamiliar JSON blob, this three-step routine saves a lot of "why does my query return nothing?" debugging time:

  1. Paste the response into the JSON Beautifier to get a clean indented view and understand the shape of the data.
  2. Run it through the JSON Validator to confirm it's well-formed — a malformed payload will silently produce empty results and send you chasing the wrong problem.
  3. Switch to the JSONPath tool and iterate on your expression until you're extracting exactly what you need.

Quick Reference: Syntax That Covers 80% of Cases

  • $ — root element
  • .key — child key
  • ..key — recursive search for key at any depth
  • [*] — all array elements
  • [0] — first element; [-1] — last element
  • [0,2] — elements at index 0 and 2
  • [?(@.price < 10)] — filter where price is less than 10
  • @.key — current node's key (used inside filter expressions)

For edge cases and implementation differences across languages, the JSONPath guide on jsonindenter.com covers the full spec with annotated examples worth bookmarking.

When JSONPath Is the Wrong Tool

JSONPath is read-only — it queries and extracts, it doesn't mutate. If you need to patch a JSON document in place (add a field, replace a value, remove a key), that's what JSON Patch is designed for. The two tools are complementary: JSONPath to find, JSON Patch to modify.

Also worth knowing: JSONPath implementations vary across languages. jsonpath-ng in Python, jsonpath-plus in JavaScript, and Jayway in Java each have subtle differences. RFC 9535 (published in 2024) is working to standardize the spec, but for production code it's worth testing your expressions against the specific library you're targeting.

JSONPath Is Worth Adding to Your Toolkit

The argument for JSONPath isn't that it's magic — it's that it's composable and readable. A well-written JSONPath expression communicates intent at a glance. Nested loops require reading to the end before you understand what's being extracted.

It's also portable: the same expression works in JavaScript, Python, Java, and tools like Postman, AWS CloudFormation, and Kubernetes JSON patches. Learning it once pays off across your entire stack.


What's the most complex JSON query you've had to write? Did you reach for JSONPath, or did you end up with custom traversal logic you later regretted?


Free tools used in this post:

  • JSONPath Evaluator — test JSONPath expressions against any JSON payload, results highlighted live
  • JSON Beautifier — format and indent raw JSON for easy reading
  • JSON Validator — confirm your JSON is well-formed before querying it
  • JSON Patch — apply RFC 6902 patches to modify JSON structures in place
  • All tools — client-side, no sign-up, nothing leaves your browser