0
# Data Querying
1
2
Core querying functionality for finding elements, paths, and nodes in JavaScript objects using JSONPath expressions. Supports the full JSONPath syntax including wildcards, array slicing, filtering with script expressions, and recursive descent.
3
4
## Capabilities
5
6
### Query Function
7
8
Find elements in an object matching a JSONPath expression and return their values.
9
10
```javascript { .api }
11
/**
12
* Find elements matching JSONPath expression
13
* @param {Object} obj - Target object to query (must be an object)
14
* @param {string} pathExpression - JSONPath expression string
15
* @param {number} [count] - Optional limit for number of results
16
* @returns {Array} Array of matching values, or empty array if none matched
17
*/
18
function query(obj, pathExpression, count);
19
```
20
21
**Usage Examples:**
22
23
```javascript
24
const jp = require('jsonpath');
25
26
const data = {
27
store: {
28
book: [
29
{ author: "Nigel Rees", title: "Sayings of the Century", price: 8.95 },
30
{ author: "Evelyn Waugh", title: "Sword of Honour", price: 12.99 },
31
{ author: "Herman Melville", title: "Moby Dick", price: 8.99 },
32
{ author: "J. R. R. Tolkien", title: "Lord of the Rings", price: 22.99 }
33
],
34
bicycle: { color: "red", price: 19.95 }
35
}
36
};
37
38
// Get all authors
39
const authors = jp.query(data, '$..author');
40
// Result: ['Nigel Rees', 'Evelyn Waugh', 'Herman Melville', 'J. R. R. Tolkien']
41
42
// Get all prices
43
const prices = jp.query(data, '$..price');
44
// Result: [8.95, 12.99, 8.99, 22.99, 19.95]
45
46
// Get books cheaper than 10
47
const cheapBooks = jp.query(data, '$..book[?(@.price<10)]');
48
// Result: [{ author: "Nigel Rees", title: "Sayings of the Century", price: 8.95 }, ...]
49
50
// Limit results with count parameter
51
const firstTwoAuthors = jp.query(data, '$..author', 2);
52
// Result: ['Nigel Rees', 'Evelyn Waugh']
53
```
54
55
### Paths Function
56
57
Find paths to elements matching a JSONPath expression. Returns arrays of keys representing the location of each match.
58
59
```javascript { .api }
60
/**
61
* Find paths to elements matching JSONPath expression
62
* @param {Object} obj - Target object to query (must be an object)
63
* @param {string} pathExpression - JSONPath expression string
64
* @param {number} [count] - Optional limit for number of paths returned
65
* @returns {Array<Array>} Array of path arrays, where each path is array of keys
66
*/
67
function paths(obj, pathExpression, count);
68
```
69
70
**Usage Examples:**
71
72
```javascript
73
const jp = require('jsonpath');
74
75
// Get paths to all authors
76
const authorPaths = jp.paths(data, '$..author');
77
// Result: [
78
// ['$', 'store', 'book', 0, 'author'],
79
// ['$', 'store', 'book', 1, 'author'],
80
// ['$', 'store', 'book', 2, 'author'],
81
// ['$', 'store', 'book', 3, 'author']
82
// ]
83
84
// Get paths to all items in store
85
const storePaths = jp.paths(data, '$.store.*');
86
// Result: [
87
// ['$', 'store', 'book'],
88
// ['$', 'store', 'bicycle']
89
// ]
90
91
// Limit paths with count parameter
92
const firstThreePaths = jp.paths(data, '$..*', 3);
93
// Result: [['$', 'store'], ['$', 'store', 'book'], ['$', 'store', 'bicycle']]
94
```
95
96
### Nodes Function
97
98
Find elements and their corresponding paths matching a JSONPath expression. Returns objects containing both the path and value for each match.
99
100
```javascript { .api }
101
/**
102
* Find elements and their paths matching JSONPath expression
103
* @param {Object} obj - Target object to query (must be an object)
104
* @param {string} pathExpression - JSONPath expression string
105
* @param {number} [count] - Optional limit for number of nodes returned
106
* @returns {Array<Object>} Array of node objects with {path: Array, value: any} structure
107
*/
108
function nodes(obj, pathExpression, count);
109
```
110
111
**Usage Examples:**
112
113
```javascript
114
const jp = require('jsonpath');
115
116
// Get nodes for all authors
117
const authorNodes = jp.nodes(data, '$..author');
118
// Result: [
119
// { path: ['$', 'store', 'book', 0, 'author'], value: 'Nigel Rees' },
120
// { path: ['$', 'store', 'book', 1, 'author'], value: 'Evelyn Waugh' },
121
// { path: ['$', 'store', 'book', 2, 'author'], value: 'Herman Melville' },
122
// { path: ['$', 'store', 'book', 3, 'author'], value: 'J. R. R. Tolkien' }
123
// ]
124
125
// Get nodes for all books
126
const bookNodes = jp.nodes(data, '$.store.book[*]');
127
// Result: [
128
// { path: ['$', 'store', 'book', 0], value: { author: "Nigel Rees", ... } },
129
// { path: ['$', 'store', 'book', 1], value: { author: "Evelyn Waugh", ... } },
130
// ...
131
// ]
132
133
// Filter and get first matching node only
134
const expensiveBookNode = jp.nodes(data, '$..book[?(@.price>20)]', 1);
135
// Result: [{ path: ['$', 'store', 'book', 3], value: { author: "J. R. R. Tolkien", ... } }]
136
```
137
138
## JSONPath Expression Syntax
139
140
The library supports comprehensive JSONPath syntax:
141
142
### Basic Operators
143
- `$` - Root object/element
144
- `@` - Current object/element (used in filters)
145
- `.property` - Child member access
146
- `..property` - Recursive descendant search
147
- `*` - Wildcard for all properties/elements
148
- `[n]` - Array index access
149
- `['property']` - Bracketed property access
150
151
### Advanced Operators
152
- `[start:end:step]` - Array slicing (Python-style)
153
- `[index1,index2,...]` - Union operator for multiple indices
154
- `[?(@.property)]` - Filter expression (elements with property)
155
- `[?(@.property==value)]` - Filter expression (property equals value)
156
- `[?(@.property<value)]` - Filter expression (property less than value)
157
- `[?(@.property>value && @.other<value)]` - Complex filter expressions
158
- `[(@.length-1)]` - Script expressions for dynamic indices
159
160
### Example Expressions
161
- `$.store.book[*].author` - All book authors
162
- `$..author` - All authors anywhere in the structure
163
- `$.store.*` - All direct children of store
164
- `$..book[2]` - Third book (0-indexed)
165
- `$..book[-1:]` - Last book using slice
166
- `$..book[0,1]` - First two books using union
167
- `$..book[:2]` - First two books using slice
168
- `$..book[?(@.price<10)]` - Books cheaper than 10
169
- `$..*` - All elements in the structure
170
171
## Error Handling
172
173
All query functions validate their inputs:
174
175
- Throws `AssertionError` if `obj` is not an object
176
- Throws `AssertionError` if `pathExpression` is not a string
177
- Returns empty array `[]` if no matches found
178
- Returns empty array `[]` if `count` is 0
179
- Throws `Error` for invalid JSONPath syntax during parsing