Debian Codegraph @

eutils/json.go

raw
1 // ===========================================================================
2 //
3 // PUBLIC DOMAIN NOTICE
4 // National Center for Biotechnology Information (NCBI)
5 //
6 // This software/database is a "United States Government Work" under the
7 // terms of the United States Copyright Act. It was written as part of
8 // the author's official duties as a United States Government employee and
9 // thus cannot be copyrighted. This software/database is freely available
10 // to the public for use. The National Library of Medicine and the U.S.
11 // Government do not place any restriction on its use or reproduction.
12 // We would, however, appreciate having the NCBI and the author cited in
13 // any work or product based on this material.
14 //
15 // Although all reasonable efforts have been taken to ensure the accuracy
16 // and reliability of the software and data, the NLM and the U.S.
17 // Government do not and cannot warrant the performance or results that
18 // may be obtained by using this software or data. The NLM and the U.S.
19 // Government disclaim all warranties, express or implied, including
20 // warranties of performance, merchantability or fitness for any particular
21 // purpose.
22 //
23 // ===========================================================================
24 //
25 // File Name: json.go
26 //
27 // Author: Jonathan Kans
28 //
29 // ==========================================================================
30
31 package eutils
32
33 import (
34 "encoding/json"
35 "github.com/gedex/inflector"
36 "html"
37 "io"
38 "os"
39 "runtime"
40 "strconv"
41 "strings"
42 )
43
44 // JSONConverter parses JSON stream into XML object stream
45 func JSONConverter(inp io.Reader, set, rec, nest string) <-chan string {
46
47 if inp == nil {
48 return nil
49 }
50
51 tks := make(chan string, chanDepth)
52 out := make(chan string, chanDepth)
53 if tks == nil || out == nil {
54 DisplayError("Unable to create JSON converter channels")
55 os.Exit(1)
56 }
57
58 tokenizeJSON := func(inp io.Reader, tks chan<- string) {
59
60 // close channel when all tokens have been sent
61 defer close(tks)
62
63 // use token decoder from encoding/json package
64 dec := json.NewDecoder(inp)
65 if dec == nil {
66 DisplayError("Unable to create JSON Decoder")
67 os.Exit(1)
68 }
69 dec.UseNumber()
70
71 for {
72 t, err := dec.Token()
73 if err == io.EOF {
74 return
75 }
76 if err != nil {
77 DisplayError("Unable to read JSON token '%s'", err)
78 os.Exit(1)
79 }
80
81 // type switch performs sequential type assertions until match is found
82 switch v := t.(type) {
83 case json.Delim:
84 // opening or closing braces (for objects) or brackets (for arrays)
85 tks <- string(v)
86 case string:
87 str := v
88 if HasAdjacentSpacesOrNewline(str) {
89 str = CompressRunsOfSpaces(str)
90 }
91 tks <- str
92 case json.Number:
93 tks <- v.String()
94 case float64:
95 tks <- strconv.FormatFloat(v, 'f', -1, 64)
96 case bool:
97 if v {
98 tks <- "true"
99 } else {
100 tks <- "false"
101 }
102 case nil:
103 tks <- "null"
104 default:
105 tks <- t.(string)
106 }
107 }
108 }
109
110 // opt is used for anonymous top-level objects, anon for anonymous top-level arrays
111 opt := "opt"
112 anon := "anon"
113 if rec != "" {
114 // override record delimiter
115 opt = rec
116 anon = rec
117 }
118
119 flatL := false
120 elemL := false
121 depthL := false
122 pluralL := false
123 singularL := false
124
125 flatR := false
126 elemR := false
127 depthR := false
128 pluralR := false
129 singularR := false
130
131 lft, rgt := SplitInTwoLeft(nest, ",")
132
133 switch lft {
134 case "flat":
135 flatL = true
136 case "element", "elem", "_E":
137 elemL = true
138 case "depth", "deep", "level":
139 depthL = true
140 case "plural", "name":
141 pluralL = true
142 case "singular", "single":
143 singularL = true
144 case "recurse", "recursive", "same":
145 default:
146 flatL = true
147 }
148
149 switch rgt {
150 case "flat":
151 flatR = true
152 case "element", "elem", "_E":
153 elemR = true
154 case "depth", "deep", "level":
155 depthR = true
156 case "plural", "name":
157 pluralR = true
158 case "singular", "single":
159 singularR = true
160 case "recurse", "recursive", "same":
161 default:
162 flatR = true
163 }
164
165 // convertJSON sends XML records down a channel
166 convertJSON := func(tks <-chan string, out chan<- string) {
167
168 // close channel when all tokens have been processed
169 defer close(out)
170
171 // ensure that XML tags are legal (initial digit allowed by xtract for biological data in JSON)
172 fixTag := func(tag string) string {
173
174 if tag == "" {
175 return tag
176 }
177
178 okay := true
179 for _, ch := range tag {
180 if !inElement[ch] {
181 okay = false
182 }
183 }
184 if okay {
185 return tag
186 }
187
188 var temp strings.Builder
189
190 // replace illegal characters with underscore
191 for _, ch := range tag {
192 if inElement[ch] {
193 temp.WriteRune(ch)
194 } else {
195 temp.WriteRune('_')
196 }
197 }
198
199 return temp.String()
200 }
201
202 // closure silently places local variable pointer onto inner function call stack
203 var buffer strings.Builder
204
205 // array to speed up indentation
206 indentSpaces := []string{
207 "",
208 " ",
209 " ",
210 " ",
211 " ",
212 " ",
213 " ",
214 " ",
215 " ",
216 " ",
217 }
218
219 indent := 0
220 if set != "" {
221 indent = 1
222 }
223
224 // indent a specified number of spaces
225 doIndent := func(indt int) {
226 i := indt
227 for i > 9 {
228 buffer.WriteString(" ")
229 i -= 10
230 }
231 if i < 0 {
232 return
233 }
234 buffer.WriteString(indentSpaces[i])
235 }
236
237 count := 0
238
239 // recursive function definitions
240 var parseObject func(tag string)
241 var parseArray func(tag, pfx string, lvl int)
242
243 // recursive descent parser uses mutual recursion
244 parseValue := func(tag, pfx, tkn string, lvl int) {
245
246 switch tkn {
247 case "{":
248 if flatR {
249 parseObject(tag)
250 } else if lvl > 0 {
251 // JSON object within JSON array creates recursive XML objects
252 doIndent(indent)
253 indent++
254 tg := tag
255 if pluralR {
256 tg = inflector.Pluralize(tag)
257 }
258 buffer.WriteString("<")
259 buffer.WriteString(tg)
260 buffer.WriteString(">\n")
261 if depthR {
262 parseObject(pfx + "_" + strconv.Itoa(lvl))
263 } else if elemR {
264 sfx := ""
265 for range lvl {
266 sfx += "_E"
267 }
268 parseObject(pfx + sfx)
269 } else if singularR {
270 parseObject(inflector.Singularize(pfx))
271 } else {
272 parseObject(pfx)
273 }
274 indent--
275 doIndent(indent)
276 buffer.WriteString("</")
277 buffer.WriteString(tg)
278 buffer.WriteString(">\n")
279 } else {
280 parseObject(tag)
281 }
282 // no break needed, would use fallthrough to explicitly cause program control to flow to the next case
283 case "[":
284 if flatL {
285 parseArray(tag, pfx, lvl+1)
286 } else if lvl > 0 {
287 // nested JSON arrays create recursive XML objects
288 doIndent(indent)
289 indent++
290 tg := tag
291 if pluralL {
292 tg = inflector.Pluralize(tag)
293 }
294 buffer.WriteString("<")
295 buffer.WriteString(tg)
296 buffer.WriteString(">\n")
297 if depthL {
298 parseArray(pfx+"_"+strconv.Itoa(lvl), tag, lvl+1)
299 } else if elemL {
300 sfx := ""
301 for range lvl {
302 sfx += "_E"
303 }
304 parseArray(pfx+sfx, tag, lvl+1)
305 } else if singularL {
306 parseArray(inflector.Singularize(pfx), tag, lvl+1)
307 } else {
308 parseArray(tag, pfx, lvl+1)
309 }
310 indent--
311 doIndent(indent)
312 buffer.WriteString("</")
313 buffer.WriteString(tg)
314 buffer.WriteString(">\n")
315 } else {
316 parseArray(tag, pfx, lvl+1)
317 }
318 case "}", "]":
319 // should not get here, decoder tracks nesting of braces and brackets
320 case "":
321 // empty value string generates self-closing object
322 doIndent(indent)
323 buffer.WriteString("<")
324 buffer.WriteString(tag)
325 buffer.WriteString("/>\n")
326 default:
327 // write object and contents to string builder
328 doIndent(indent)
329 tkn = strings.TrimSpace(tkn)
330 tkn = html.EscapeString(tkn)
331 buffer.WriteString("<")
332 buffer.WriteString(tag)
333 buffer.WriteString(">")
334 buffer.WriteString(tkn)
335 buffer.WriteString("</")
336 buffer.WriteString(tag)
337 buffer.WriteString(">\n")
338 }
339
340 count++
341 if count > 1000 {
342 count = 0
343 txt := buffer.String()
344 if txt != "" {
345 // send current result through output channel
346 out <- txt
347 }
348 buffer.Reset()
349 }
350 }
351
352 parseObject = func(tag string) {
353
354 doIndent(indent)
355 indent++
356 buffer.WriteString("<")
357 buffer.WriteString(tag)
358 buffer.WriteString(">\n")
359
360 for {
361 // shadowing tag variable inside for loop does not step on value of tag argument in outer scope
362 tag, ok := <-tks
363 if !ok {
364 break
365 }
366
367 if tag == "}" || tag == "]" {
368 break
369 }
370
371 tag = fixTag(tag)
372
373 tkn, ok := <-tks
374 if !ok {
375 break
376 }
377
378 if tkn == "}" || tkn == "]" {
379 break
380 }
381
382 parseValue(tag, tag, tkn, 0)
383 }
384
385 indent--
386 doIndent(indent)
387 buffer.WriteString("</")
388 buffer.WriteString(tag)
389 buffer.WriteString(">\n")
390 }
391
392 parseArray = func(tag, pfx string, lvl int) {
393
394 for {
395 tkn, ok := <-tks
396 if !ok {
397 break
398 }
399
400 if tkn == "}" || tkn == "]" {
401 break
402 }
403
404 parseValue(tag, pfx, tkn, lvl)
405 }
406 }
407
408 if set != "" {
409 out <- "<" + set + ">"
410 }
411
412 // process stream of catenated top-level JSON objects or arrays
413 for {
414 tkn, ok := <-tks
415 if !ok {
416 break
417 }
418 if tkn == "{" {
419 parseObject(opt)
420 } else if tkn == "[" {
421 parseArray(anon, anon, 0)
422 } else {
423 break
424 }
425
426 txt := buffer.String()
427 if txt != "" {
428 // send remaining result through output channel
429 out <- txt
430 }
431
432 buffer.Reset()
433
434 runtime.Gosched()
435 }
436
437 if set != "" {
438 out <- "</" + set + ">"
439 }
440 }
441
442 // launch single tokenizer goroutine
443 go tokenizeJSON(inp, tks)
444
445 // launch single converter goroutine
446 go convertJSON(tks, out)
447
448 return out
449 }
450
451 // JSONtoXML converts JSON to an XML string
452 func JSONtoXML(jsn, set, rec, nest string) string {
453
454 return StringToXML(jsn, func(inp io.Reader) <-chan string {
455 return JSONConverter(inp, set, rec, nest)
456 })
457 }