-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathisjson
executable file
·82 lines (75 loc) · 1.22 KB
/
isjson
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#!/usr/bin/env bash
#
# Synopsis:
# Is a file or standard input well formed json?
# Usage:
# isjson <x.json
# isjson x.json
# Exit Status:
# 0 input is well formed json
# 1 input is not well formed json
# 2 unknown error
# Note:
# Extend to more than one file!
#
die()
{
echo "ERROR: $@" >&2
exit 2
}
# valid path to eexecutable
is_exec()
{
EXE=$1
which $EXE >/dev/null 2>&1
STATUS=$?
test $STATUS -le 1 && return $STATUS
die "which $EXE failed: exit status=$STATUS"
}
case $# in
0)
;;
1)
# sadly, file existence exit with status 1
test -r $1 || die "can not read file: $1"
;;
*)
die "wrong number of arguments: got $#, expected < 2"
;;
esac
# Find executable "python", which is python2.
# otherwise, use python3, if exists.
# the pain never ends.
PYTHON=python
if is_exec $PYTHON; then
true
else
PYTHON=python3
if is_exec $PYTHON; then
true
else
die 'cannot find python exec'
fi
fi
$PYTHON -m json.tool $1 >/dev/null 2>&1
STATUS=$?
case $STATUS in
0)
ANSWER="YES: valid"
;;
1)
ANSWER="NO: invalid"
;;
127)
die "exit status=127: is python installed?"
;;
*)
die "python json failed: exit status=$STATUS"
;;
esac
if [ $# = 0 ]; then
echo "$ANSWER json"
else
echo "$ANSWER json: $1"
fi
exit $STATUS