JSONPath-Tester

Testen und validieren Sie JSONPath-Ausdrücke gegen JSON-Dokumente in Echtzeit

What is JSONPath?

JSONPath is a query language for extracting and filtering data from JSON documents, analogous to how XPath navigates XML structures. Originally proposed by Stefan Goessner in 2007 and later formalized as RFC 9535 by the IETF, JSONPath provides a concise expression syntax for traversing nested objects and arrays without writing imperative code. Developers use JSONPath expressions in API testing frameworks, configuration systems, log analysis pipelines, and anywhere structured JSON data needs to be queried declaratively. This tool lets you write JSONPath expressions against sample JSON and instantly see the matching results — useful for developing queries interactively before embedding them in production code.

JSONPath Syntax Fundamentals

Every JSONPath expression starts with the root identifier $, which represents the top-level element of the JSON document. From the root, you navigate deeper into the structure using dot notation or bracket notation. Dot notation ($.store.book) is concise and readable for simple property access, while bracket notation ($['store']['book']) handles property names that contain special characters, spaces, or start with digits.

Wildcards and recursive descent: The wildcard operator * matches all members of an object or all elements of an array at the current level. For example, $.store.* returns all direct children of the store object. The recursive descent operator .. searches through all descendants regardless of nesting depth — $..price finds every property named "price" anywhere in the document, whether it sits at the top level or buried inside nested arrays of objects. This is particularly powerful for extracting values from deeply nested or irregularly structured API responses.

Array access: Arrays support index-based access with square brackets. Single indices ($.books[0]) return one element, negative indices ($.books[-1]) count from the end, and slice notation ($.books[0:3]) extracts a range. Multiple indices can be specified with commas: $.books[0,2,4] selects elements at positions 0, 2, and 4 simultaneously. The slice syntax follows the pattern [start:end:step], where omitted values default to the array boundaries.

Filter Expressions and Logical Operators

Filter expressions are JSONPath's most powerful feature, enabling conditional selection of elements based on their values. Filters appear inside square brackets prefixed with a question mark: $.books[?(@.price < 20)] selects all books where the price property is less than 20. The @ symbol represents the current element being evaluated — it is the filter's iteration variable, analogous to this in JavaScript callbacks or the loop variable in a for-each construct.

Comparison operators: JSONPath supports the standard comparison operators: == (equality), != (inequality), < (less than), <= (less than or equal), > (greater than), and >= (greater than or equal). String comparisons use lexicographic ordering. Equality checks work across types — comparing a string to a number always evaluates to false without throwing an error, which makes filters safe against type mismatches in heterogeneous data.

Logical operators: Combine multiple conditions using && (logical AND) and || (logical OR). Negation uses ! before a condition. Complex queries like $.products[?(@.stock > 0 && @.price < 50)] find all in-stock products under fifty units of currency. Parentheses group conditions to control evaluation order when mixing AND and OR operators. Some implementations also support a match() function for regular expression matching against string values.

Existence checks: Testing whether a property exists uses the pattern $.items[?(@.discount)], which selects items that have a discount property regardless of its value. Combined with negation ($.items[?(!@.archived)]), this filters out elements with specific flags — useful for querying active records from datasets that use boolean flags for soft deletion.

JSONPath vs jq and Other Query Tools

JSONPath and jq both query JSON documents, but they differ significantly in design philosophy, syntax, and capabilities. JSONPath is a path expression language designed for embedding in configuration files, test assertions, and API specifications — it is declarative and read-only. jq is a full-featured command-line processor with a Turing-complete language that supports transformation, construction of new documents, conditionals, and function definitions.

Syntax differences: JSONPath uses $.store.books[0].title while jq uses .store.books[0].title (no dollar sign root). JSONPath filters use [?(@.price > 10)] while jq uses select(.price > 10). JSONPath's recursive descent .. has no direct equivalent in jq — you would use .. | .price? // empty or the recurse function. The syntactic difference matters when choosing a tool: JSONPath expressions are typically shorter and more intuitive for simple extractions, while jq provides more power for complex transformations.

Capability comparison: JSONPath is strictly a query language — it extracts data but cannot modify, restructure, or aggregate it. jq can construct entirely new JSON documents, apply map/reduce operations, perform arithmetic, join multiple documents, and format output. If you need to extract a value from a response, JSONPath is sufficient. If you need to transform the response structure, aggregate fields, or pipe results into further processing, jq is the appropriate tool.

Ecosystem integration: JSONPath is widely supported in API testing tools (Postman, REST Assured, Karate), monitoring systems (Datadog, Grafana), and configuration languages (Kubernetes JSONPath templates, AWS Step Functions). jq is primarily a command-line tool used in shell scripts and CI/CD pipelines. Choosing between them depends on where the query will execute: embedded in application code or configuration, JSONPath is standard; in a shell pipeline processing files, jq is more natural.

Common Use Cases and Expression Patterns

JSONPath expressions appear across development workflows wherever JSON data needs to be queried without writing parsing code:

API response extraction: When testing REST APIs, JSONPath assertions verify that responses contain expected values at specific paths. An assertion like $.data.users[0].email confirms the response structure matches the expected schema. Testing frameworks use JSONPath to extract values for chaining requests — pulling a token from a login response to use in subsequent authenticated calls.

Configuration navigation: Kubernetes uses JSONPath in kubectl get commands with the -o jsonpath flag to extract specific fields from resource definitions. For example, kubectl get pods -o jsonpath='{.items[*].metadata.name}' lists all pod names. This avoids piping through jq when simple extraction suffices.

Log and event filtering: Structured logging in JSON format (common in cloud-native applications) benefits from JSONPath queries that extract relevant fields from high-volume log streams. Queries like $.events[?(@.level == "error")].message filter error messages from mixed-severity event arrays without loading entire documents into memory.

Data pipeline validation: ETL pipelines that process JSON use JSONPath expressions to validate intermediate results. Checking that transformed documents contain required fields at expected paths catches pipeline errors early. Combining JSONPath with JSON Schema validation provides both structural and value-level assurance.

Code Examples

JSONPath queries against a sample document

// Sample JSON document
{
  "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", "price": 8.99, "isbn": "0-553-21311-3" },
      { "category": "fiction", "author": "J. R. R. Tolkien",
        "title": "The Lord of the Rings", "price": 22.99, "isbn": "0-395-19395-8" }
    ],
    "bicycle": { "color": "red", "price": 19.95 }
  }
}

// Expression: $.store.book[*].author
// Result: ["Nigel Rees", "Evelyn Waugh", "Herman Melville", "J. R. R. Tolkien"]

// Expression: $..price
// Result: [8.95, 12.99, 8.99, 22.99, 19.95]

// Expression: $.store.book[?(@.price < 10)]
// Result: [{"category":"reference","author":"Nigel Rees",...}, {"category":"fiction","author":"Herman Melville",...}]

// Expression: $.store.book[?(@.isbn)]
// Result: [{"category":"fiction","author":"Herman Melville",...}, {"category":"fiction","author":"J. R. R. Tolkien",...}]

// Expression: $.store.book[0:2]
// Result: [first two books]

// Expression: $.store.book[-1].title
// Result: "The Lord of the Rings"

Using JSONPath in JavaScript with the jsonpath-plus library

import { JSONPath } from 'jsonpath-plus';

const data = {
  users: [
    { name: "Alice", role: "admin", active: true },
    { name: "Bob", role: "editor", active: true },
    { name: "Charlie", role: "viewer", active: false }
  ]
};

// Extract all user names
const names = JSONPath({ path: '$.users[*].name', json: data });
// Result: ["Alice", "Bob", "Charlie"]

// Find active admins
const activeAdmins = JSONPath({
  path: '$.users[?(@.role=="admin" && @.active==true)]',
  json: data
});
// Result: [{ name: "Alice", role: "admin", active: true }]

// Get the count of active users
const activeUsers = JSONPath({
  path: '$.users[?(@.active==true)]',
  json: data
});
console.log(`Active users: ${activeUsers.length}`);
// Output: "Active users: 2"

Standards & Specifications

  • RFC 9535 — JSONPath: Query Expressions for JSON — the IETF standard defining JSONPath syntax, semantics, and normalization rules
  • Stefan Goessner's Original JSONPath Article — The 2007 article that introduced JSONPath as an XPath analog for JSON, defining the original syntax conventions

Häufig Gestellte Fragen

What is JSONPath?

JSONPath is a query language for JSON that allows you to extract specific data from JSON documents using path expressions. It's similar to XPath for XML and provides a standardized way to navigate and query JSON structures. JSONPath is commonly used for parsing API responses, extracting data from configuration files, and filtering complex JSON documents.

What's the difference between $ and $..?

The $ symbol refers to the root element of the JSON document - it's the starting point for all JSONPath expressions. The $.. operator is the recursive descent operator that searches for matching fields at any depth in the JSON structure. For example, $..name will find all fields named 'name' regardless of where they appear in the document hierarchy.

How do I filter array elements?

Use filter expressions with the syntax $[?(@.condition)] to select array elements that match a condition. The @ symbol represents the current element being tested. For example, $[?(@.price < 10)] selects all array elements where the price field is less than 10. You can use comparison operators like <, >, <=, >=, ==, and != in filter expressions.

Can I use wildcards in JSONPath?

Yes! The * wildcard matches all elements at the current level. Use $.* to select all properties of an object, and $[*] to select all elements of an array. For example, $.store.book[*].title would get the title of every book in the store.book array.

What are array slices in JSONPath?

Array slices let you select a range of elements using the syntax $[start:end]. For example, $[0:3] selects elements at indices 0, 1, and 2 (the end index is exclusive). You can also use negative indices: $[-3:] selects the last three elements. Slices work similarly to Python array slicing.

Is my data sent to a server?

No, all JSONPath evaluation happens entirely in your browser. Your JSON data and expressions never leave your device. This ensures complete privacy and security for sensitive information like API responses or configuration files.

Why does my expression return no results?

Common reasons include: incorrect path syntax (check for typos), the field doesn't exist at that path, case sensitivity (field names are case-sensitive), or the JSON structure doesn't match your expectations. Try using simpler expressions like $ or $.* first to verify your JSON structure, then build up to more complex paths.