NBash

Форк
0
212 строк · 4.8 Кб
1
#!/bin/sh
2

3
# License: MIT or Apache
4
# Homepage: http://github.com/dominictarr/JSON.sh
5

6
throw() {
7
  echo "$*" >&2
8
  exit 1
9
}
10

11
BRIEF=0
12
LEAFONLY=0
13
PRUNE=0
14
NO_HEAD=0
15
NORMALIZE_SOLIDUS=0
16

17
usage() {
18
  echo
19
  echo "Usage: JSON.sh [-b] [-l] [-p] [-s] [-h]"
20
  echo
21
  echo "-p - Prune empty. Exclude fields with empty values."
22
  echo "-l - Leaf only. Only show leaf nodes, which stops data duplication."
23
  echo "-b - Brief. Combines 'Leaf only' and 'Prune empty' options."
24
  echo "-n - No-head. Do not show nodes that have no path (lines that start with [])."
25
  echo "-s - Remove escaping of the solidus symbol (straight slash)."
26
  echo "-h - This help text."
27
  echo
28
}
29

30
parse_options() {
31
  set -- "$@"
32
  local ARGN=$#
33
  while [ "$ARGN" -ne 0 ]
34
  do
35
    case $1 in
36
      -h) usage
37
          exit 0
38
      ;;
39
      -b) BRIEF=1
40
          LEAFONLY=1
41
          PRUNE=1
42
      ;;
43
      -l) LEAFONLY=1
44
      ;;
45
      -p) PRUNE=1
46
      ;;
47
      -n) NO_HEAD=1
48
      ;;
49
      -s) NORMALIZE_SOLIDUS=1
50
      ;;
51
      ?*) echo "ERROR: Unknown option."
52
          usage
53
          exit 0
54
      ;;
55
    esac
56
    shift 1
57
    ARGN=$((ARGN-1))
58
  done
59
}
60

61
# compatibility
62
awk_egrep () {
63
  local pattern_string=$1
64

65
  a='' gawk '{
66
    while ($0) {
67
      start=match($0, pattern);
68
      token=substr($0, start, RLENGTH);
69
      print token;
70
      $0=substr($0, start+RLENGTH);
71
    }
72
  }' pattern="$pattern_string"
73
}
74

75
tokenize () {
76
  local GREP
77
  local ESCAPE
78
  local CHAR
79

80
  if echo "test string" | grep -E -ao --color=never "test" >/dev/null 2>&1
81
  then
82
    GREP='grep -E -ao --color=never'
83
  else
84
    GREP='grep -E -ao'
85
  fi
86

87
  if echo "test string" | grep -E -o "test" >/dev/null 2>&1
88
  then
89
    ESCAPE='(\\[^u[:cntrl:]]|\\u[0-9a-fA-F]{4})'
90
    CHAR='[^[:cntrl:]"\\]'
91
  else
92
    GREP=awk_egrep
93
    ESCAPE='(\\\\[^u[:cntrl:]]|\\u[0-9a-fA-F]{4})'
94
    CHAR='[^[:cntrl:]"\\\\]'
95
  fi
96

97
  local STRING="\"$CHAR*($ESCAPE$CHAR*)*\""
98
  local NUMBER='-?(0|[1-9][0-9]*)([.][0-9]*)?([eE][+-]?[0-9]*)?'
99
  local KEYWORD='null|false|true'
100
  local SPACE='[[:space:]]+'
101

102
  # Force zsh to expand $A into multiple words
103
  local is_wordsplit_disabled=$(unsetopt 2>/dev/null | grep -c '^shwordsplit$')
104
  if [ $is_wordsplit_disabled != 0 ]; then setopt shwordsplit; fi
105
  $GREP "$STRING|$NUMBER|$KEYWORD|$SPACE|." | grep -E -v "^$SPACE$"
106
  if [ $is_wordsplit_disabled != 0 ]; then unsetopt shwordsplit; fi
107
}
108

109
parse_array () {
110
  local index=0
111
  local ary=''
112
  read -r token
113
  case "$token" in
114
    ']') ;;
115
    *)
116
      while :
117
      do
118
        parse_value "$1" "$index"
119
        index=$((index+1))
120
        ary="$ary""$value" 
121
        read -r token
122
        case "$token" in
123
          ']') break ;;
124
          ',') ary="$ary," ;;
125
          *) throw "EXPECTED , or ] GOT ${token:-EOF}" ;;
126
        esac
127
        read -r token
128
      done
129
      ;;
130
  esac
131
  [ "$BRIEF" -eq 0 ] && value=$(printf '[%s]' "$ary") || value=
132
  :
133
}
134

135
parse_object () {
136
  local key
137
  local obj=''
138
  read -r token
139
  case "$token" in
140
    '}') ;;
141
    *)
142
      while :
143
      do
144
        case "$token" in
145
          '"'*'"') key=$token ;;
146
          *) throw "EXPECTED string GOT ${token:-EOF}" ;;
147
        esac
148
        read -r token
149
        case "$token" in
150
          ':') ;;
151
          *) throw "EXPECTED : GOT ${token:-EOF}" ;;
152
        esac
153
        read -r token
154
        parse_value "$1" "$key"
155
        obj="$obj$key:$value"        
156
        read -r token
157
        case "$token" in
158
          '}') break ;;
159
          ',') obj="$obj," ;;
160
          *) throw "EXPECTED , or } GOT ${token:-EOF}" ;;
161
        esac
162
        read -r token
163
      done
164
    ;;
165
  esac
166
  [ "$BRIEF" -eq 0 ] && value=$(printf '{%s}' "$obj") || value=
167
  :
168
}
169

170
parse_value () {
171
  local jpath="${1:+$1,}$2" isleaf=0 isempty=0 print=0
172
  case "$token" in
173
    '{') parse_object "$jpath" ;;
174
    '[') parse_array  "$jpath" ;;
175
    # At this point, the only valid single-character tokens are digits.
176
    ''|[!0-9]) throw "EXPECTED value GOT ${token:-EOF}" ;;
177
    *) value=$token
178
       # if asked, replace solidus ("\/") in json strings with normalized value: "/"
179
       [ "$NORMALIZE_SOLIDUS" -eq 1 ] && value=$(echo "$value" | sed 's#\\/#/#g')
180
       isleaf=1
181
       [ "$value" = '""' ] && isempty=1
182
       ;;
183
  esac
184
  [ "$value" = '' ] && return
185
  [ "$NO_HEAD" -eq 1 ] && [ -z "$jpath" ] && return
186

187
  [ "$LEAFONLY" -eq 0 ] && [ "$PRUNE" -eq 0 ] && print=1
188
  [ "$LEAFONLY" -eq 1 ] && [ "$isleaf" -eq 1 ] && [ $PRUNE -eq 0 ] && print=1
189
  [ "$LEAFONLY" -eq 0 ] && [ "$PRUNE" -eq 1 ] && [ "$isempty" -eq 0 ] && print=1
190
  [ "$LEAFONLY" -eq 1 ] && [ "$isleaf" -eq 1 ] && \
191
    [ $PRUNE -eq 1 ] && [ $isempty -eq 0 ] && print=1
192
  [ "$print" -eq 1 ] && printf "[%s]\t%s\n" "$jpath" "$value"
193
  :
194
}
195

196
parse () {
197
  read -r token
198
  parse_value
199
  read -r token
200
  case "$token" in
201
    '') ;;
202
    *) throw "EXPECTED EOF GOT $token" ;;
203
  esac
204
}
205

206
if ([ "$0" = "$BASH_SOURCE" ] || ! [ -n "$BASH_SOURCE" ]);
207
then
208
  parse_options "$@"
209
  tokenize | parse
210
fi
211

212
# vi: expandtab sw=2 ts=2
213

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.