A fast command-line interface tool for working with JSON data, designed as a single-file Node.js script with no external dependencies.
npx @tessl/cli install tessl/npm-json@11.0.00
# JSON
1
2
JSON is a fast command-line interface tool for working with JSON data, designed as a single-file Node.js script with no external dependencies. It enables users to pretty-print JSON, extract specific values using natural JavaScript-like syntax, validate JSON syntax with detailed error reporting, filter and transform JSON data through inline expressions, and process streaming JSON data efficiently.
3
4
## Package Information
5
6
- **Package Name**: json
7
- **Package Type**: npm
8
- **Language**: JavaScript (Node.js)
9
- **Installation**: `npm install -g json`
10
- **Binary**: `json` command
11
12
## Core Imports
13
14
For module usage (limited API):
15
16
```javascript
17
const json = require('json');
18
```
19
20
ES modules (if supported):
21
22
```javascript
23
import * as json from 'json';
24
```
25
26
## Basic Usage
27
28
### Command Line Interface (Primary Usage)
29
30
```bash
31
# Pretty-print JSON
32
echo '{"name":"trent","age":38}' | json
33
# {
34
# "name": "trent",
35
# "age": 38
36
# }
37
38
# Extract specific values
39
echo '{"name":"trent","age":38}' | json name
40
# trent
41
42
# Filter and transform data
43
echo '[{"age":38},{"age":4}]' | json -c 'this.age > 21'
44
# [{"age":38}]
45
46
# Process array with tabular output
47
echo '[{"name":"trent","age":38},{"name":"ewan","age":4}]' | json -a name age
48
# trent 38
49
# ewan 4
50
```
51
52
### Module Usage (Limited)
53
54
```javascript
55
const json = require('json');
56
57
// Get version
58
console.log(json.getVersion()); // "11.0.0"
59
60
// Parse lookup expressions
61
const lookup = json.parseLookup('user.name');
62
console.log(lookup); // ['user', 'name']
63
64
// Apply lookups to data
65
const data = { user: { name: 'Alice' } };
66
const result = json.lookupDatum(data, lookup);
67
console.log(result); // 'Alice'
68
```
69
70
## Capabilities
71
72
### Command Line Processing
73
74
The primary interface is the `json` command which processes JSON data from stdin or files.
75
76
```bash { .api }
77
json [OPTIONS] [LOOKUPS...]
78
json -f FILE [OPTIONS] [LOOKUPS...]
79
```
80
81
**Core Command Line Options:**
82
83
```bash { .api }
84
# Input/Output Options
85
-f FILE # Specify input file (instead of stdin)
86
-I, --in-place # Edit file in-place (requires -f FILE)
87
-q, --quiet # Don't warn if input isn't valid JSON
88
89
# Processing Options
90
-H # Drop HTTP header blocks
91
-g, --group # Group adjacent objects/arrays
92
--merge # Merge adjacent objects (shallow)
93
--deep-merge # Merge adjacent objects (deep)
94
-M, --items # Itemize object into key/value pairs
95
-a, --array # Process as array with tabular output
96
-A # Process as single object (override array processing)
97
98
# Filtering and Execution Options
99
-e CODE # Execute JavaScript code on input
100
-c CODE # Filter input with JavaScript condition
101
-k, --keys # Output object keys
102
-n, --validate # Just validate JSON (no output)
103
104
# Output Format Options
105
-o MODE, --output MODE # Output mode (jsony, json, inspect, compact)
106
-i # Shortcut for -o inspect
107
-j # Shortcut for -o json
108
-0, -2, -4 # Set indentation level
109
-d DELIM # Delimiter for tabular output
110
111
# Lookup Options
112
-D DELIM # Delimiter for lookups (default: '.')
113
114
# Help Options
115
-h, --help # Print help
116
--version # Print version
117
```
118
119
### JSON Processing Features
120
121
Core JSON processing capabilities available via command line.
122
123
**Pretty Printing:**
124
- Default "jsony" output: JSON with unquoted single strings
125
- Pure JSON output with configurable indentation
126
- Node.js util.inspect format with colors
127
- Compact experimental format
128
129
**Data Extraction:**
130
- Dot notation lookups: `field.subfield`
131
- Array indexing: `array.0` or `array[0]`
132
- Negative array indexing: `array.-1` (Python-style)
133
- Bracket notation for complex keys: `["field.with.dots"]`
134
- Custom lookup delimiters
135
136
**Data Transformation:**
137
- JavaScript code execution with `-e` option
138
- Conditional filtering with `-c` option
139
- Object key extraction with `-k`
140
- Array processing with tabular output using `-a`
141
142
**Advanced Processing:**
143
- HTTP header stripping for REST API responses
144
- Object grouping and array concatenation
145
- Object merging (shallow and deep)
146
- Key-value itemization for objects
147
- Streaming support for large files
148
149
### Validation and Error Handling
150
151
JSON validation with detailed error reporting.
152
153
```bash { .api }
154
# Validate JSON with detailed errors
155
json -n, --validate # Just validate, no output
156
json -q # Quiet mode for silent validation
157
```
158
159
**Error Reporting Features:**
160
- Line and column position for syntax errors
161
- Context highlighting with error markers
162
- Graceful handling of non-JSON input
163
- HTTP header detection and processing
164
165
### Module API (Limited)
166
167
The package provides a limited module API for programmatic access.
168
169
```javascript { .api }
170
/**
171
* Main entry point function that processes command line arguments
172
* @param {string[]} argv - Command line arguments array
173
*/
174
function main(argv);
175
176
/**
177
* Returns the version string
178
* @returns {string} Version number
179
*/
180
function getVersion();
181
182
/**
183
* Parse lookup string into array of lookup components
184
* @param {string} lookup - The lookup expression (e.g., "user.name")
185
* @param {string} [lookupDelim='.'] - Optional delimiter character (default: '.')
186
* @returns {Array<string|number>} Array of lookup components
187
*/
188
function parseLookup(lookup, lookupDelim);
189
190
/**
191
* Apply a parsed lookup to data object
192
* @param {*} datum - The data to lookup from
193
* @param {Array<string|number>} lookup - Parsed lookup array from parseLookup()
194
* @returns {*} The result of the lookup, or undefined if not found
195
*/
196
function lookupDatum(datum, lookup);
197
198
/**
199
* Print datum with formatting options (DEPRECATED - use stringifyDatum instead)
200
* @param {*} datum - Data to print
201
* @param {object} opts - Output options
202
* @param {string} sep - Separator string
203
* @param {boolean} alwaysPrintSep - Always print separator flag
204
* @deprecated This function is deprecated in favor of other output methods
205
*/
206
function printDatum(datum, opts, sep, alwaysPrintSep);
207
```
208
209
### Lookup System
210
211
Powerful lookup system for extracting data from JSON structures.
212
213
**Lookup Syntax:**
214
- **Dot notation**: `user.profile.name`
215
- **Array indexing**: `users.0.name` or `users[0].name`
216
- **Negative indexing**: `users.-1` (last element)
217
- **Bracket notation**: `["field.with.dots"]` or `['field-with-hyphens']`
218
- **Custom delimiters**: `-D/` allows `user/profile/name`
219
220
**Special Cases:**
221
- Negative array indices for Python-style access
222
- Quoted strings for complex property names
223
- Mixed notation: `users[0].profile["display-name"]`
224
225
### Stream Processing
226
227
Efficient processing of large JSON files and streams.
228
229
```bash { .api }
230
# Stream processing with grouping and array output
231
json -ga [LOOKUPS...] # Group + array processing for streaming
232
233
# Process multiple files
234
cat *.json | json -g [OPTIONS] [LOOKUPS...]
235
```
236
237
**Streaming Features:**
238
- Automatic object/array grouping for concatenated JSON
239
- Memory-efficient processing of large files
240
- Support for newline-separated JSON objects (like log files)
241
- HTTP header detection in streams
242
243
### Environment Variables
244
245
Configuration through environment variables.
246
247
```bash { .api }
248
JSON_EXEC=vm # Use legacy vm execution mode for -e/-c options
249
```
250
251
## Types
252
253
```javascript { .api }
254
// Output mode constants
255
const OM_JSONY = 1; // Default "jsony" output mode
256
const OM_JSON = 2; // Pure JSON output mode
257
const OM_INSPECT = 3; // Node.js util.inspect output mode
258
const OM_COMPACT = 4; // Compact output mode
259
260
// Output mode mapping
261
const OM_FROM_NAME = {
262
'jsony': OM_JSONY,
263
'json': OM_JSON,
264
'inspect': OM_INSPECT,
265
'compact': OM_COMPACT
266
};
267
268
// Options object structure (internal)
269
/**
270
* @typedef {Object} ParsedOptions
271
* @property {string[]} args - Remaining command line arguments
272
* @property {boolean} help - Help flag
273
* @property {boolean} quiet - Quiet mode flag
274
* @property {boolean} dropHeaders - Drop HTTP headers flag
275
* @property {string[]} exeSnippets - JavaScript execution snippets from -e
276
* @property {string[]} condSnippets - JavaScript condition snippets from -c
277
* @property {number} outputMode - Output mode (OM_JSONY, OM_JSON, etc.)
278
* @property {number|string} jsonIndent - JSON indentation (number of spaces or '\t' for tab)
279
* @property {boolean|null} array - Array processing flag (null = auto-detect)
280
* @property {string} delim - Delimiter for tabular output (default: ' ')
281
* @property {string} lookupDelim - Delimiter for lookup parsing (default: '.')
282
* @property {boolean} items - Itemize objects into key-value pairs flag
283
* @property {boolean} outputKeys - Output object keys flag
284
* @property {boolean} group - Group adjacent objects/arrays flag
285
* @property {string|null} merge - Merge mode ('shallow', 'deep', or null)
286
* @property {string[]} inputFiles - Input file paths from -f options
287
* @property {boolean} validate - Validation-only mode flag
288
* @property {boolean} inPlace - In-place editing flag
289
*/
290
```
291
292
## Installation Examples
293
294
**Global installation for CLI usage:**
295
```bash
296
npm install -g json
297
```
298
299
**Manual installation:**
300
```bash
301
cd ~/bin
302
curl -L https://github.com/trentm/json/raw/master/lib/json.js > json
303
chmod 755 json
304
```
305
306
**Module usage in package.json:**
307
```json
308
{
309
"dependencies": {
310
"json": "^11.0.0"
311
}
312
}
313
```
314
315
## Usage Examples
316
317
**REST API Processing:**
318
```bash
319
# Pretty-print API response
320
curl -s https://api.github.com/repos/user/repo | json
321
322
# Extract specific fields
323
curl -s https://api.github.com/repos/user/repo | json name description
324
325
# Filter with conditions
326
curl -s https://api.github.com/repos/user/repo/issues | json -c 'this.state === "open"'
327
```
328
329
**File Processing:**
330
```bash
331
# Format JSON file
332
json -f config.json
333
334
# In-place editing
335
json -I -f config.json -e 'this.port = 8080'
336
337
# Extract configuration values
338
json -f package.json version scripts.start
339
```
340
341
**Data Analysis:**
342
```bash
343
# Tabular output from array
344
echo '[{"name":"Alice","age":30},{"name":"Bob","age":25}]' | json -a name age
345
346
# Get object keys
347
echo '{"a":1,"b":2,"c":3}' | json -k
348
349
# Process log files
350
cat app.log | json -ga timestamp level message
351
```
352
353
**Advanced Processing:**
354
```bash
355
# Object itemization for key-value processing
356
echo '{"users":{"alice":{"age":30},"bob":{"age":25}}}' | json users -M -a key value.age
357
358
# Merging configuration files
359
cat base.json override.json | json --merge
360
361
# Validation with detailed errors
362
cat invalid.json | json -n
363
```