Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Newer
Older
100755 103 lines (95 sloc) 2.143 kB
8a954c0 @dominictarr make JSON.sh into one self contained script
authored
1
2 throw () {
3 echo "$*" >&2
4 exit 1
5 }
6
7 tokenize () {
8 local ESCAPE='(\\[^u[:cntrl:]]|\\u[0-9a-fA-F]{4})'
9 local CHAR='[^[:cntrl:]"\\]'
10 local STRING="\"$CHAR*($ESCAPE$CHAR*)*\""
11 local NUMBER='-?(0|[1-9][0-9]*)([.][0-9]*)?([eE][+-]?[0-9]*)?'
12 local KEYWORD='null|false|true'
13 local SPACE='[[:space:]]+'
14 egrep -ao "$STRING|$NUMBER|$KEYWORD|$SPACE|." --color=never |
15 egrep -v "^$SPACE$" # eat whitespace
16 }
17
18 parse_array () {
19 local index=0
20 local ary=''
21 read -r token
22 case "$token" in
23 ']') ;;
24 *)
25 while :
26 do
27 parse_value "$1" "$index"
28 let index=$index+1
29 ary="$ary""$value"
30 read -r token
31 case "$token" in
32 ']') break ;;
33 ',') ary="$ary," ;;
34 *) throw "EXPECTED , or ] GOT ${token:-EOF}" ;;
35 esac
36 read -r token
37 done
38 ;;
39 esac
360b592 @dominictarr fixed issue 11
authored
40 value=`printf '[%s]' "$ary"`
8a954c0 @dominictarr make JSON.sh into one self contained script
authored
41 }
42
43 parse_object () {
44 local key
45 local obj=''
46 read -r token
47 case "$token" in
48 '}') ;;
49 *)
50 while :
51 do
52 case "$token" in
53 '"'*'"') key=$token ;;
54 *) throw "EXPECTED string GOT ${token:-EOF}" ;;
55 esac
56 read -r token
57 case "$token" in
58 ':') ;;
59 *) throw "EXPECTED : GOT ${token:-EOF}" ;;
60 esac
61 read -r token
62 parse_value "$1" "$key"
63 obj="$obj$key:$value"
64 read -r token
65 case "$token" in
66 '}') break ;;
67 ',') obj="$obj," ;;
68 *) throw "EXPECTED , or } GOT ${token:-EOF}" ;;
69 esac
70 read -r token
71 done
72 ;;
73 esac
74 value=`printf '{%s}' "$obj"`
75 }
76
77 parse_value () {
78 local jpath="${1:+$1,}$2"
79 case "$token" in
80 '{') parse_object "$jpath" ;;
81 '[') parse_array "$jpath" ;;
82 # At this point, the only valid single-character tokens are digits.
83 ''|[^0-9]) throw "EXPECTED value GOT ${token:-EOF}" ;;
84 *) value=$token ;;
85 esac
86 printf "[%s]\t%s\n" "$jpath" "$value"
87 }
88
89 parse () {
90 read -r token
91 parse_value
92 read -r token
93 case "$token" in
94 '') ;;
95 *) throw "EXPECTED EOF GOT $token" ;;
96 esac
97 }
98
99 if [ $0 = $BASH_SOURCE ];
100 then
101 tokenize | parse
102 fi
Something went wrong with that request. Please try again.