-
Notifications
You must be signed in to change notification settings - Fork 0
/
cli.js
executable file
·68 lines (55 loc) · 1.2 KB
/
cli.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#!/usr/bin/env node
const meow = require('meow')
const stdin = require('get-stdin')
const cli = meow(`$ jsonpp --help
Usage
$ jsonpp [--space] <string>
$ echo <string> | jsonpp [--space]
Options
-s, --space Space
Examples
$ jsonpp '{"number":42,"string":"string"}'
{
"number": 42,
"string": "string"
}
$ echo '{"number":42,"string":"string"}' | jsonpp -s 4
{
"number": 42,
"string": "string"
}
`, {
flags: {
space: {
type: 'number',
alias: 's',
default: 2
}
}
})
const {input: [input], flags} = cli
if (!input && process.stdin.isTTY) {
console.error('Please specify text to parse')
process.exit(1)
}
const space = Number.parseInt(flags.space, 10)
const pretty = ({data = '', space = 2}) => {
const replacer = (key, value) => {
const regex = /"/
try {
return (typeof value === 'string' && regex.test(value)) ?
replacer(key, JSON.parse(value)) : value
} catch {
return value
}
}
console.log(JSON.stringify(data, replacer, space))
}
(async () => {
if (input) {
pretty({data: input, space})
} else {
const data = await stdin()
pretty({data, space})
}
})()