forked from lhunath/scripts
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparseJSON
More file actions
executable file
·222 lines (191 loc) · 6.89 KB
/
parseJSON
File metadata and controls
executable file
·222 lines (191 loc) · 6.89 KB
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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
#! /usr/bin/env bash
# ___________________________________________________________________________ #
# #
# plainjson -- A utility for converting JSON into plain data and back. #
# #
# #
# Licensed under the Apache License, Version 2.0 (the "License"); #
# you may not use this file except in compliance with the License. #
# You may obtain a copy of the License at #
# #
# http://www.apache.org/licenses/LICENSE-2.0 #
# #
# Unless required by applicable law or agreed to in writing, software #
# distributed under the License is distributed on an "AS IS" BASIS, #
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #
# See the License for the specific language governing permissions and #
# limitations under the License. #
# ___________________________________________________________________________ #
# #
# #
# Copyright 2010, lhunath #
# * http://www.lhunath.com #
# * Maarten Billemont #
source bashlib
### Parse JSON input data and output data in a format that's easily parsed by a bash while-read loop.
#
# The output describes the JSON hierarchy. Objects are preceded by a dot (.), array indices are preceded by a hash (#) and values are preceded by an equal sign (=).
# By default, the output will be line-based (each element in the hierarchy terminated by a newline).
# If your data contains newlines or you want a safer output format, consider -z or -d to change the delimitor.
# If this code parses your JSON incorrectly, turn on verbose mode with -v, fix the script and let me know: lhunath@lyndir.com
# Default configuration.
delimitor=$'\n'
# Options to change configuration.
while getopts :zd:vo arg; do
case $arg in
z) delimitor='\0';;
d) delimitor=$OPTARG;;
v) _logVerbosity=3;;
o) jsonout=1;;
esac
done
# Utilities.
isObject() {
local context=$1
[[ $context = [^0-9]* ]]
}
isArray() {
local context=$1
! isObject "$context"
}
pushContext() {
contextStack+=("$1")
}
popContext() {
local topIndex=$(( ${#contextStack[@]} - 1 ))
unset 'contextStack[topIndex]'
}
peekContext() {
local topIndex=$(( ${#contextStack[@]} - 1 ))
printf '%s' "${contextStack[topIndex]}"
}
writeData() {
local type
# Check if we have anything new to show
(( dirty )) && {
for context in "${contextStack[@]}"; do
# Is this context element an object(.) or array(#)?
isObject "$context" && type='.' || type='#'
printf '%s%s' "$type" "$context"
done
printf "=%s${delimitor:-\0}" "$data"
}
data=
dirty=0
}
parseJSON() {
dirty=1
# Read loop.
while IFS= read -r -d '' -n1 char; do
if [[ $char = '"' ]]; then
if (( quoted = !quoted )); then
dbg "Quotes start."
else
dbg "Quotes end: %s" "$data"
fi
continue
fi
if (( ! quoted )); then
if [[ $char = '{' ]]; then
dbg "Object starts."
dirty=1
continue
elif [[ $char = '}' ]]; then
dbg "Object ends: %s" "$(peekContext)"
writeData
popContext
continue
elif [[ $char = '[' ]]; then
dbg "Array starts."
pushContext 0
continue
elif [[ $char = ']' ]]; then
dbg "Array ends: %s" "$(peekContext)"
writeData
popContext
continue
elif [[ $char = ':' ]]; then
dbg "Key: %s" "$data"
pushContext "$data"
data=
continue
elif [[ $char = ',' ]]; then
dbg "Element ends: %s" "$(peekContext)"
writeData
context=$(peekContext)
popContext
if isArray "$context"; then
pushContext "$((context + 1))"
fi
dirty=1
continue
elif [[ $char = [$' \n\r\t\v'] ]]; then
# Ignore unquoted whitespace
continue
fi
fi
data+=$char
done
}
startJSONContext() {
local context=$1
dbg 'Starting context: %s' "$context"
if isObject "$context"; then
printf "{'%s':" "$context"
else
printf '['
fi
}
endJSONContexts() {
for (( p = $#; p > 0; --p )); do
context=${@:p:1}
dbg 'Ending context: %s' "$context"
if isObject "$context"; then
printf '}'
else
printf ']'
fi
done
}
# WIP
parsePlain() {
firstElement=()
while IFS= read -r -d "$delimitor"; do
key=${REPLY%%=*} data=${REPLY#*=}
IFS='#.' read -r -a newContextStack <<< "$key"
newContextStack=("${newContextStack[@]:1}")
dbg 'key:%s data:<%s>' "$key" "$data"
for s in "${!newContextStack[@]}"; do
newContext=${newContextStack[s]}
if (( s >= ${#oldContextStack[@]} )); then
# Start new context
startJSONContext "$newContext"
firstElement[s]=1
dbg 'firstElements: %s' "${firstElement[*]}"
#elif [[ ${oldContextStack[s]} != "$newContext" ]]; then
# End old contexts up to s
#endJSONContexts "${oldContextStack[@]:s}"
#startJSONContext "$newContext"
#firstElement=("${firstElement[@]:0:s}" 1)
#dbg 'firstElements: %s' "${firstElement[*]}"
fi
done
endJSONContexts "${oldContextStack[@]:s+1}"
firstElement=("${firstElement[@]:0:s+1}")
dbg 'firstElements: %s' "${firstElement[*]}"
if (( ${firstElement[s]} )); then
printf '"%s"' "$data"
else
printf ',"%s"' "$data"
fi
firstElement[s]=0
dbg 'firstElements: %s' "${firstElement[*]}"
oldContextStack=("${newContextStack[@]}")
done
endJSONContexts "${oldContextStack[@]}"
}
if (( jsonout )); then
parsePlain
else
parseJSON
fi