-
Notifications
You must be signed in to change notification settings - Fork 0
/
jsonReParse.py
executable file
·328 lines (243 loc) · 10.8 KB
/
jsonReParse.py
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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
"""
JSON parsing ... at least initially for Watson-for-Genomics reports ...
"""
__author__ = "Sheila M Reynolds"
__version__ = "0.0.1"
__status__ = "Prototype"
import argparse
import json
import sys
import time
import uuid
# ----------------------------------------------------------------------------------------------------
inputFilename = ''
outFh = None
maxDepth = 0
ithGen = 0
genList = []
naStrings = ['[]', '{}', 'na', 'NA', ':', '::', '[""]', "['']", \
'EditMe', 'Please edit me', \
'None', 'None.', 'None found', 'Not determined', \
'Unknown', 'Unknown.']
skipLabels = [ 'LegalNotice' ]
# ----------------------------------------------------------------------------------------------------
def quickStrip(s):
if (str(s) == 'nan'):
return ('')
t = ''
for u in s.splitlines():
if (len(u) > 0):
if (len(t) > 0):
t += ' ' + u.strip()
else:
t += u.strip()
tabSplit = t.split('\t')
t = ''
for u in tabSplit:
if (len(u) > 0):
if (len(t) > 0):
t += ' ' + u.strip()
else:
t += u.strip()
t = t.strip()
if ( t.find(',') >= 0 ):
if ( t.find('"') >= 0 ): t = t.replace('"',"'")
if ( t.find('"') < 0 ):
t = '"' + t + '"'
else:
print ( " FATAL ERROR with commas and quotes in a string !!! " )
print ( " <%s> " % t )
return (t)
# ----------------------------------------------------------------------------------------------------
def isContainerNode(key,value):
cFlag = True
print ( " DDDD : in isContainerNode ... ", key, str(type(value)) )
## if this is a dict, we consider that a 'container'
if isinstance(value,dict): return ( cFlag )
## if this is a list, we consider that a 'container'
if isinstance(value,list): return ( cFlag )
## this may not matter too much, but if there isn't going to
## actually be any 'data' coming from this (key,value) pair
## then we can also return 'True'
try:
textString = quickStrip(str(value))
except:
print ( " DDDD : what now ??? ", type(value), value )
print ( " ERROR !!! BAILING !!! " )
sys.exit(-1)
if ( len(textString)==0 or textString in naStrings ): return ( cFlag )
cFlag = False
return ( cFlag )
# ----------------------------------------------------------------------------------------------------
def isContainer2Node(key,value):
cFlag = True
print ( " DDDD : in isContainer2Node ... ", key, str(type(value)) )
## if this is a dict, check if the next layer is a container ...
if isinstance(value,dict):
for k,v in value.items():
return ( isContainerNode(k,v) )
## if this is a list, check if the next layer is a container ...
if isinstance(value,list):
for v in value:
return ( isContainerNode(None,v) )
cFlag = False
return ( cFlag )
# ----------------------------------------------------------------------------------------------------
def handleNodeData(key,value,gpID,pID):
print ( " HND : in handleNodeData ... ", gpID, pID, key, str(type(value)) )
## if the incoming 'thing' (aka node) is a dict, then we go the next level
## since in JSON, 'dicts' are what define 'levels'
## (or at least that's our working interpretation)
if isinstance(value,dict):
dLen = len(value)
print ( " HND : this value is a dict of length %d ... " % dLen )
if ( dLen > 1 ):
eID = uuid.uuid4()
print ( " HND : generating a new UUID ... ", eID )
print ( " HND : calling handleNextLevel ... ", pID, eID )
handleNextLevel(key,value,pID,eID)
else:
eID = None
print ( " HND : NOT generating a new UUID at this time ... " )
print ( " HND : calling handleNextLevel ... ", gpID, pID )
handleNextLevel(key,value,gpID,pID)
## if, on the other hand, the incoming 'thing' is a list, then we loop over
## the things in the list and recursively call this function ...
elif isinstance(value,list):
vLen = len(value)
print ( " HND : this value is a list of length %d ... " % vLen )
try:
print ( " HND : --> list of ", str(type(value[0])) )
except:
pass
## loop over contents of list:
for a in value:
print ( " HND : calling handleNodeData ... ", gpID, pID )
handleNodeData(key,a,gpID,pID)
## and if it is neither a dict nor a list, then it must be something fairly
## simple and we can just handle it right now
else:
try:
textString = quickStrip(str(value))
except:
print ( " HND : what now ??? ", type(value), value )
print ( " ERROR !!! BAILING !!! " )
sys.exit(-1)
if ( len(textString) < 1 ):
print ( " HND : zero length textString ??? !!! " )
if ( textString in naStrings ):
print ( " HND : textString is in naStrings ", textString )
if ( len(textString)==0 or textString in naStrings ): return()
longLabel = ''
if ( len(genList) > 0 ): longLabel = ' > '.join(genList)
longLabel = longLabel.strip()
parentLabel = ''
elementLabel = ''
try:
elementLabel = genList[-1]
parentLabel = genList[-2]
except:
pass
if ( parentLabel in skipLabels or elementLabel in skipLabels ):
print ( " HND : label in skipLabels ", parentLabel, elementLabel )
return()
print ( " HND : writing string value {%s = %s} " % ( longLabel, textString ) )
outString = inputFilename + '\t' + str(ithGen) + '\t' \
+ str(gpID) + '\t' + str(pID) + '\t' \
+ longLabel + '\t' + parentLabel + '\t' + elementLabel + '\t' \
+ textString
outFh.write ( "%s\n" % outString )
print ( " HND : %s " % outString )
print ( " \n\n" )
print ( " HND : leaving handleNodeData ... " )
return()
# ----------------------------------------------------------------------------------------------------
# inspired by:
# https://stackoverflow.com/questions/28194703/recursive-xml-parsing-python-using-elementtree
def handleNextLevel(key,value,gpID,pID):
global ithGen, genList
print ( " HNL : in handleNextLevel ... ", ithGen, genList, key, str(type(value)) )
## at this point we do one of two main things: if it is NOT a dict, we handle
## this node's 'data' ... if it IS a dict, then we loop over its items() ...
if ( not isinstance(value,dict) ):
## we should never get here w/o value being of type dict !!!
print ( " DO WE EVER ACTUALLY GET HERE ??? !!! " )
sys.exit(-1)
else:
## YES this IS a dict ...
bkpGen = ithGen
bkpList = genList
## loop over all *next* (key,value) pairs beneath the incoming 'node':
for nkey,nvalue in value.items():
print ( " HNL : --> key = <%s> : value is %s " % ( nkey, str(type(nvalue)) ) )
ithGen = bkpGen + 1
genList = bkpList + [ nkey ]
print ( " HNL : calling handleNodeData ... ", gpID, pID )
handleNodeData(nkey,nvalue,gpID,pID)
## back up ...
ithGen = bkpGen
genList = bkpList
return()
# ----------------------------------------------------------------------------------------------------
def main(args):
global inputFilename, outFh, maxDepth
## print ( args )
if ( not args.inputFile.endswith(".json") ):
print ( " is this a JSON file ??? <%s> " % args.inputFile )
print ( " ERROR !!! BAILING !!! " )
sys.exit(-1)
inputFilename = args.inputFile
allowedModes = [ 'w', 'w+', 'a', 'a+' ]
if ( args.writeMode not in allowedModes ):
print ( " ERROR: invalid writeMode <%s> " % args.writeMode )
print ( " ERROR !!! BAILING !!! " )
sys.exit(-1)
try:
outFh = open ( args.outputFile, args.writeMode )
except:
print ( " FAILED to open output file <%s> with <%s> " % ( args.outputFile, args.writeMode ) )
print ( " ERROR !!! BAILING !!! " )
sys.exit(-1)
maxDepth = args.maxDepth
if ( args.colLabels.lower().startswith('t') ):
outString = 'inputJSONfile\tjsonDepth\tparentID\tbundleID\tfull_label\tparent_label\telement_label\telement_text'
outFh.write ( "%s\n" % outString )
try:
inFh = open ( inputFilename, 'r' )
jdata = json.load(inFh)
#XML xmlp = ET.XMLParser(encoding="latin-1")
#XML tree = ET.parse(inputFilename,parser=xmlp)
except:
print ( " FAILED to parse input JSON file ??? <%s> " % inputFilename )
print ( " ERROR !!! BAILING !!! " )
sys.exit(-1)
## handle any information that exists at the root level...
## the first two parameters in handleNodeData are a (key,value)
## but at the 'root' there is no 'key' and the 'value' is the entire dict...
root = jdata
print ( " CCCC : calling handleNodeData from main ... ", None, None )
handleNodeData(None,root,None,None)
if ( 0 ):
## and then go to the next level (this is the recursive function)
print ( " CCCC : calling handleNextLevel from main ... ", None, None )
handleNextLevel(None,root,None,None)
# ----------------------------------------------------------------------------------------------------
if __name__ == '__main__':
t0 = time.time()
parser = argparse.ArgumentParser()
parser.add_argument('-f', '--inputFileName', action='store', help='input JSON data file',
required=True, dest='inputFile', type=str)
parser.add_argument('-o', '--outputFileName', action='store', help='output TSV data file',
required=True, dest='outputFile', type=str)
parser.add_argument('-w', '--writeMode', action='store', help='output TSV data file',
required=False, dest='writeMode', type=str, default='w+')
parser.add_argument('-d', '--maxDepth', action='store', help='maximum depth to output TSV',
required=False, dest='maxDepth', type=int, default=99)
parser.add_argument('-l', '--colLabels', action='store', help='write column labels to output TSV',
required=False, dest='colLabels', type=str, default="True")
parser.add_argument('-s', '--schemaFileName', action='store', help='output JSON schema file',
required=False, dest='schemaFile', type=str)
args = parser.parse_args()
main(args)
print ( "\n\n\n" )
# ----------------------------------------------------------------------------------------------------