Utility Coder
← Back to Blog
Data Processing12 min read

XPath vs JSONPath: Querying XML and JSON Data

Master data querying with XPath for XML and JSONPath for JSON. Learn syntax, patterns, and practical examples for both query languages.

By Andy Pham

XPath vs JSONPath: Querying XML and JSON Data

When working with structured data, you need powerful query languages to extract specific information. XPath queries XML documents, while JSONPath does the same for JSON. This guide covers both.

Quick Comparison

Feature XPath JSONPath
Data Format XML JSON
Root / or // $
Child / or // . or []
Wildcards * *
Array Index [n] (1-based) [n] (0-based)
Filtering [predicate] [?(expression)]
Recursive // ..

XPath Fundamentals

Basic Syntax

/root/element          <!-- Absolute path -->
//element              <!-- Find anywhere -->
element/@attribute     <!-- Get attribute -->
element/text()         <!-- Get text content -->

Common Patterns

<!-- All books -->
//book

<!-- Books with price > 20 -->
//book[price > 20]

<!-- First book title -->
//book[1]/title

<!-- Books by category -->
//book[@category='fiction']

<!-- Titles containing "Guide" -->
//title[contains(text(), 'Guide')]

XPath Example

Given this XML:

<library>
  <book category="tech">
    <title>JavaScript Guide</title>
    <author>John Doe</author>
    <price>29.99</price>
  </book>
  <book category="fiction">
    <title>The Novel</title>
    <author>Jane Smith</author>
    <price>19.99</price>
  </book>
</library>

Queries:

//book/title                    → All titles
//book[@category='tech']/title  → "JavaScript Guide"
//book[price<25]/title          → "The Novel"
//author                        → All authors
count(//book)                   → 2

JSONPath Fundamentals

Basic Syntax

$                   // Root object
$.property          // Child property
$..property         // Recursive descent
$[0]                // Array index
$[*]                // All array elements
$[?(@.price<10)]    // Filter

Common Patterns

// All books
$.store.books[*]

// All prices anywhere
$..price

// First book
$.store.books[0]

// Filter by condition
$.store.books[?(@.price < 20)]

// Multiple properties
$.store.books[*]['title','author']

JSONPath Example

Given this JSON:

{
  "store": {
    "books": [
      { "title": "JavaScript Guide", "price": 29.99, "category": "tech" },
      { "title": "The Novel", "price": 19.99, "category": "fiction" }
    ],
    "location": "Sydney"
  }
}

Queries:

$.store.books[*].title           → ["JavaScript Guide", "The Novel"]
$.store.books[0]                 → First book object
$..price                         → [29.99, 19.99]
$.store.books[?(@.price<25)]     → [{"title": "The Novel", ...}]
$.store.books[?(@.category=='tech')].title → ["JavaScript Guide"]

JavaScript Implementation

XPath in Browser

function xpath(expression, context = document) {
  const result = document.evaluate(
    expression,
    context,
    null,
    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,
    null
  );

  const nodes = [];
  for (let i = 0; i < result.snapshotLength; i++) {
    nodes.push(result.snapshotItem(i));
  }
  return nodes;
}

// Parse XML
const parser = new DOMParser();
const xml = parser.parseFromString(xmlString, 'text/xml');

// Query
const titles = xpath('//book/title', xml);
titles.forEach(t => console.log(t.textContent));

JSONPath with Library

import { JSONPath } from 'jsonpath-plus';

const data = { store: { books: [...] } };

// Query
const titles = JSONPath({ path: '$.store.books[*].title', json: data });
console.log(titles); // ["JavaScript Guide", "The Novel"]

// With filter
const cheap = JSONPath({
  path: '$.store.books[?(@.price < 25)]',
  json: data
});

When to Use Each

Use XPath When:

  • Working with XML/HTML documents
  • Web scraping with tools like Selenium
  • XSLT transformations
  • Processing SOAP APIs
  • Complex document traversal

Use JSONPath When:

  • Querying REST API responses
  • Extracting data from JSON configs
  • Testing JSON APIs (Postman, etc.)
  • Processing NoSQL database results

Advanced Techniques

XPath Axes

ancestor::div        <!-- Parent div elements -->
following-sibling::* <!-- Elements after current -->
preceding::*         <!-- All elements before -->
descendant-or-self::* <!-- Current and descendants -->

JSONPath Scripts

// Filter with multiple conditions
$.books[?(@.price < 30 && @.category == 'tech')]

// Slice notation
$.books[0:3]    // First 3 books
$.books[-1:]    // Last book

Try Our Tools

Test your queries with our free online tools:

Conclusion

Both XPath and JSONPath are essential skills for developers working with structured data. XPath excels at navigating complex XML documents, while JSONPath is perfect for modern JSON-based APIs. Master both to handle any data extraction task efficiently.

Share this article