0
# Command Line Interface
1
2
JSONPath-NG provides a command-line tool for searching JSON files using JSONPath expressions. The tool can process files or read from stdin, making it useful for scripting and data processing pipelines.
3
4
## Capabilities
5
6
### Command Line Tool
7
8
Execute JSONPath queries from the command line against JSON files or stdin input.
9
10
```python { .api }
11
def main(*argv):
12
"""
13
Main CLI function that processes command line arguments and executes JSONPath queries.
14
15
Args:
16
*argv: Command line arguments (typically sys.argv)
17
"""
18
19
def entry_point():
20
"""Entry point for the jsonpath_ng console script"""
21
22
def find_matches_for_file(expr, f):
23
"""
24
Find JSONPath matches in a JSON file.
25
26
Args:
27
expr: Parsed JSONPath expression
28
f: File object containing JSON data
29
30
Returns:
31
List of DatumInContext objects with matches
32
"""
33
34
def print_matches(matches):
35
"""
36
Print JSONPath match results to stdout.
37
38
Args:
39
matches: List of DatumInContext objects
40
"""
41
```
42
43
### Installation and Usage
44
45
The command-line tool is installed automatically with the package:
46
47
```bash
48
pip install jsonpath-ng
49
```
50
51
Usage syntax:
52
53
```bash
54
jsonpath_ng EXPRESSION [FILES...]
55
```
56
57
### Command Line Options
58
59
- **EXPRESSION**: A JSONPath expression string (required)
60
- **FILES**: One or more JSON files to search (optional, defaults to stdin)
61
62
### Usage Examples
63
64
**Search a single file:**
65
66
```bash
67
jsonpath_ng '$.users[*].name' data.json
68
```
69
70
**Search multiple files:**
71
72
```bash
73
jsonpath_ng '$.products[*].price' inventory.json catalog.json
74
```
75
76
**Search from stdin:**
77
78
```bash
79
cat data.json | jsonpath_ng '$.users[?(@.age > 18)].name'
80
```
81
82
**Using glob patterns:**
83
84
```bash
85
jsonpath_ng '$.timestamp' logs/*.json
86
```
87
88
**Complex expressions:**
89
90
```bash
91
# Find all nested email addresses
92
jsonpath_ng '$..email' contacts.json
93
94
# Union of multiple paths
95
jsonpath_ng '$.users[*].(name|email)' users.json
96
97
# Array slicing
98
jsonpath_ng '$.results[1:5]' results.json
99
```
100
101
### JSONPath Syntax Quick Reference
102
103
The CLI tool supports standard JSONPath syntax as implemented by jsonpath-ng:
104
105
**Atomics:**
106
- `$` - Root object
107
- `` `this` `` - Current object
108
109
**Operators:**
110
- `path1.path2` - Child relationship (like XPath /)
111
- `path1|path2` - Union of paths
112
- `path1..path2` - Recursive descent (somewhere in between)
113
114
**Fields:**
115
- `fieldname` - Field with specific name
116
- `*` - Any field
117
- `[start:end]` - Array slice notation
118
- `[*]` - Any array index
119
120
### Output Format
121
122
The tool outputs matching values, one per line:
123
124
```bash
125
$ echo '{"users": [{"name": "Alice"}, {"name": "Bob"}]}' | jsonpath_ng '$.users[*].name'
126
Alice
127
Bob
128
```
129
130
For complex objects, the entire object is output as JSON:
131
132
```bash
133
$ echo '{"users": [{"name": "Alice", "age": 30}]}' | jsonpath_ng '$.users[*]'
134
{"name": "Alice", "age": 30}
135
```
136
137
### Error Handling
138
139
The tool handles common error cases:
140
141
- **Invalid JSONPath syntax**: Parser error with helpful message
142
- **Invalid JSON files**: JSON parsing error
143
- **File not found**: Standard file system error
144
- **No matches**: Empty output (no error)
145
146
### Integration with Shell Pipelines
147
148
The CLI tool works well in shell pipelines:
149
150
```bash
151
# Count matching results
152
jsonpath_ng '$.items[*]' data.json | wc -l
153
154
# Extract and sort values
155
jsonpath_ng '$.users[*].name' users.json | sort
156
157
# Filter and format results
158
curl -s api/users | jsonpath_ng '$.data[*].email' | grep "@company.com"
159
160
# Pipe to other JSON tools
161
jsonpath_ng '$.products[*]' catalog.json | jq '.price'
162
```
163
164
### Console Script Registration
165
166
The tool is registered as a console script entry point:
167
168
```python { .api }
169
# In setup.py
170
entry_points={
171
'console_scripts': [
172
'jsonpath_ng=jsonpath_ng.bin.jsonpath:entry_point'
173
],
174
}
175
```
176
177
This makes the `jsonpath_ng` command available system-wide after installation.