forked from cute/JSONPretty
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJSONPretty.sh
122 lines (113 loc) · 2.79 KB
/
JSONPretty.sh
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
#!/bin/sh
# Based: https://github.com/dominictarr/JSON.sh
tabs=""
indent=0
newline="
"
throw () {
echo "$*" >&2
exit 1
}
gen_tabs () {
if [ $indent -gt 0 ]; then
tabs=`printf '%*s' "$indent" ' ' | tr ' ' "\t"`
else
tabs=''
fi
}
tokenize () {
local ESCAPE='(\\[^u[:cntrl:]]|\\u[0-9a-fA-F]{4})'
local CHAR='[^[:cntrl:]"\\]'
local STRING="\"$CHAR*($ESCAPE$CHAR*)*\""
local NUMBER='-?(0|[1-9][0-9]*)([.][0-9]*)?([eE][+-]?[0-9]*)?'
local KEYWORD='null|false|true'
local SPACE='[[:space:]]+'
grep -E -ao "$STRING|$NUMBER|$KEYWORD|$SPACE|."|grep -E -v "^$SPACE$"
}
parse_array () {
local index=0
local ary="["
read -r token
case "$token" in
']') ;;
*)
while :
do
parse_value "$1" "$index"
index=`expr $index + 1`
ary="$ary$value"
read -r token
case "$token" in
']') break ;;
',') ary="$ary," ;;
*) throw "EXPECTED , or ] GOT ${token:-EOF}" ;;
esac
read -r token
done
;;
esac
value="$ary]"
}
parse_object () {
gen_tabs
local key
local obj="{$newline"
read -r token
case "$token" in
'}') ;;
*)
while :
do
case "$token" in
'"'*'"') key=$token ;;
*) throw "EXPECTED string GOT ${token:-EOF}" ;;
esac
read -r token
case "$token" in
':') ;;
*) throw "EXPECTED : GOT ${token:-EOF}" ;;
esac
read -r token
parse_value "$1" "$key"
obj="$obj$tabs$key:$value"
read -r token
case "$token" in
'}')
indent=`expr $indent - 1`;
gen_tabs
obj="$obj$newline$tabs"
break ;;
',')
obj="$obj,$newline" ;;
*) throw "EXPECTED , or } GOT ${token:-EOF}" ;;
esac
read -r token
done
;;
esac
value="$obj}"
}
parse_value () {
local expr="${1:+$1,}$2"
gen_tabs
case "$token" in
'{')
indent=`expr $indent + 1`;
parse_object "$expr" ;;
'[')
parse_array "$expr" ;;
''|[^0-9]) throw "EXPECTED value GOT ${token:-EOF}" ;;
*) value=$token ;;
esac
}
parse () {
read -r token
parse_value
echo "$value"
read -r token
case "$token" in
'') ;;
*) throw "EXPECTED EOF GOT $token" ;;
esac
}
tokenize | parse