forked from johnkerl/miller
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mlrval_json.go
516 lines (459 loc) · 13.9 KB
/
mlrval_json.go
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
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
// ================================================================
// Mlrval implements the Unmarshaler and Marshaler interfaces needed for
// marshaling/unmarshaling to/from JSON, via the UnmarshalJSON and MarshalJSON
// methods.
//
// Please see also https://golang.org/pkg/encoding/json/
// ================================================================
package mlrval
import (
"bytes"
"encoding/json"
"fmt"
"io"
"github.com/johnkerl/miller/internal/pkg/colorizer"
"github.com/johnkerl/miller/internal/pkg/lib"
)
const JSON_INDENT_STRING string = " "
type TJSONFormatting int
const (
JSON_SINGLE_LINE = 1
JSON_MULTILINE = 2
)
// ================================================================
// The JSON decoder (https://golang.org/pkg/encoding/json/#Decoder) is quite
// nice. What we can have is:
//
// * Values: string, number, true, false, null
// * Arrays: '[' ... ']'
// * Objects: '{' ... '}'
//
// When we get the start token (if any): if it's a value that's it.
//
// Otherwise we got either array-start or object start.
//
// In the array case the decoder will deal with whitespace, commas, etc and
// return the array-values tokens while decoder.More(). Then we need to get the
// next token and verify it's close-bracket.
//
// For example on input '[1,2,3]', the start token is '['. While decoder.More()
// we get the 1,2,3. Then we read the next token and make sure it's ']'.
//
// In the object case the decoder will deal with whitespace, commas, etc and
// return the element tokens alternating key, value, key, value, while
// decoder.More(). Then we need to get the next token and verify it's
// close-bracket.
//
// For example on input '{"a":1,"b":2,"c"3]', the start token is '{'. While
// decoder.More() we get the "a",1,"b",2,"c",3. Then we read the next token and
// make sure it's '}'.
//
// In the case the input is of the form '[1,2,3][4,5,6]' -- i.e. a stream of
// valid JSON items -- we can use decoder.Buffered() to continue stream
// processing.
//
// ----------------------------------------------------------------
// json.Token holds one of the following types:
//
// * Delim, for the four JSON delimiters [ ] { }
// * bool, for JSON booleans
// * float64, for JSON numbers
// * Number, for JSON numbers
// * string, for JSON string literals
// * nil, for JSON null
//
// ----------------------------------------------------------------
// Note: we accept a sequence of valid JSON items, not just a JSON item.
// E.g. either
//
// {
// "a": 1,
// "b": 2
// }
// {
// "a": 3,
// "b": 4
// }
//
// or
//
// [
// {
// "a": 1,
// "b": 2
// },
// {
// "a": 3,
// "b": 4
// }
// ]
//
// This is so the Miller JSON record-reader can be streaming, not needing to
// ingest all records at once, and operable within a tail -f context.
// ================================================================
// ----------------------------------------------------------------
func (mv *Mlrval) UnmarshalJSON(inputBytes []byte) error {
*mv = *FromPending()
decoder := json.NewDecoder(bytes.NewReader(inputBytes))
pmv, eof, err := MlrvalDecodeFromJSON(decoder)
if eof {
return fmt.Errorf("mlr: JSON parser: unexpected premature EOF.")
}
if err != nil {
return err
}
*mv = *pmv
return nil
}
// ----------------------------------------------------------------
func MlrvalDecodeFromJSON(decoder *json.Decoder) (
mlrval *Mlrval,
eof bool,
err error,
) {
// Causes the decoder to unmarshal a number into an interface{} as a Number
// instead of as a float64.
decoder.UseNumber()
startToken, err := decoder.Token()
if err == io.EOF {
return nil, true, nil
}
if err != nil {
return nil, false, err
}
delimiter, isDelim := startToken.(json.Delim)
if !isDelim {
if startToken == nil {
return NULL, false, nil
}
sval, ok := startToken.(string)
if ok {
mlrval := FromString(sval)
return mlrval, false, nil
}
bval, ok := startToken.(bool)
if ok {
return FromBool(bval), false, nil
}
nval, ok := startToken.(json.Number)
if ok {
mlrval := FromInferredType(nval.String())
return mlrval, false, nil
}
return nil, false, fmt.Errorf(
"mlr: JSON reader internal coding error: non-delimiter token unhandled",
)
} else {
isArray := false
var expectedClosingDelimiter = ' '
var collectionType = ""
if delimiter == '[' {
isArray = true
expectedClosingDelimiter = ']'
collectionType = "JSON array"
} else if delimiter == '{' {
isArray = false
expectedClosingDelimiter = '}'
collectionType = "JSON object`"
} else {
return nil, false, fmt.Errorf(
"mlr: JSON reader: Unhandled opening delimiter \"%s\"", string(delimiter),
)
}
mv := FromPending()
if isArray {
mv = FromEmptyArray()
for decoder.More() {
element, eof, err := MlrvalDecodeFromJSON(decoder)
if eof {
// xxx constify
return nil, false, fmt.Errorf("mlr: JSON parser: unexpected premature EOF.")
}
if err != nil {
return nil, false, err
}
mv.ArrayAppend(element)
}
} else {
mv = FromEmptyMap()
for decoder.More() {
key, eof, err := MlrvalDecodeFromJSON(decoder)
if eof {
// xxx constify
return nil, false, fmt.Errorf("mlr: JSON parser: unexpected premature EOF.")
}
if err != nil {
return nil, false, err
}
if !key.IsString() {
return nil, false, fmt.Errorf(
// TODO: print out what was gotten
"mlr JSON reader: object keys must be string-valued.",
)
}
value, eof, err := MlrvalDecodeFromJSON(decoder)
if eof {
// xxx constify
return nil, false, fmt.Errorf("mlr: JSON parser: unexpected premature EOF.")
}
if err != nil {
return nil, false, err
}
// xxx check here string-valued key
mv.MapPut(key, value)
}
}
imbalanceError := fmt.Errorf(
"mlr: JSON reader: did not find closing token \"%s\" for %s",
string(expectedClosingDelimiter),
collectionType,
)
endToken, err := decoder.Token()
if err == io.EOF {
return nil, false, fmt.Errorf("mlr: JSON parser: unexpected premature EOF.")
}
if err != nil {
return nil, false, err
}
if endToken == nil {
return nil, false, imbalanceError
}
dval, ok := endToken.(json.Delim)
if !ok {
return nil, false, imbalanceError
}
if rune(dval) != expectedClosingDelimiter {
return nil, false, imbalanceError
}
return mv, false, nil
}
}
// ================================================================
func (mv *Mlrval) MarshalJSON(
jsonFormatting TJSONFormatting,
outputIsStdout bool,
) (string, error) {
return mv.marshalJSONAux(jsonFormatting, 1, outputIsStdout)
}
func (mv *Mlrval) marshalJSONAux(
jsonFormatting TJSONFormatting,
elementNestingDepth int,
outputIsStdout bool,
) (string, error) {
switch mv.Type() {
case MT_PENDING:
return mv.marshalJSONPending(outputIsStdout)
case MT_ERROR:
return mv.marshalJSONError(outputIsStdout)
case MT_ABSENT:
return mv.marshalJSONAbsent(outputIsStdout)
case MT_NULL:
return mv.marshalJSONNull(outputIsStdout)
case MT_VOID:
return mv.marshalJSONVoid(outputIsStdout)
case MT_STRING:
return mv.marshalJSONString(outputIsStdout)
case MT_INT:
return mv.marshalJSONInt(outputIsStdout)
case MT_FLOAT:
return mv.marshalJSONFloat(outputIsStdout)
case MT_BOOL:
return mv.marshalJSONBool(outputIsStdout)
case MT_ARRAY:
return mv.marshalJSONArray(jsonFormatting, elementNestingDepth, outputIsStdout)
case MT_MAP:
return mv.marshalJSONMap(jsonFormatting, elementNestingDepth, outputIsStdout)
case MT_DIM: // MT_DIM is one past the last valid type
return "", fmt.Errorf("mlr: internal coding error detected")
}
return "", fmt.Errorf("mlr: Internal coding error detected")
}
// ================================================================
// TYPE-SPECIFIC MARSHALERS
// ----------------------------------------------------------------
func (mv *Mlrval) marshalJSONPending(outputIsStdout bool) (string, error) {
lib.InternalCodingErrorIf(mv.mvtype != MT_PENDING)
return "", fmt.Errorf(
"mlr: internal coding error: pending-values should not have been produced",
)
}
// ----------------------------------------------------------------
func (mv *Mlrval) marshalJSONError(outputIsStdout bool) (string, error) {
lib.InternalCodingErrorIf(mv.mvtype != MT_ERROR)
return colorizer.MaybeColorizeValue(mv.printrep, outputIsStdout), nil
}
// ----------------------------------------------------------------
func (mv *Mlrval) marshalJSONAbsent(outputIsStdout bool) (string, error) {
lib.InternalCodingErrorIf(mv.mvtype != MT_ABSENT)
return "", fmt.Errorf(
"mlr: internal coding error: absent-values should not have been assigned",
)
}
// ----------------------------------------------------------------
func (mv *Mlrval) marshalJSONNull(outputIsStdout bool) (string, error) {
lib.InternalCodingErrorIf(mv.mvtype != MT_NULL)
return colorizer.MaybeColorizeValue("null", outputIsStdout), nil
}
// ----------------------------------------------------------------
func (mv *Mlrval) marshalJSONVoid(outputIsStdout bool) (string, error) {
lib.InternalCodingErrorIf(mv.mvtype != MT_VOID)
return colorizer.MaybeColorizeValue("\"\"", outputIsStdout), nil
}
// ----------------------------------------------------------------
func (mv *Mlrval) marshalJSONString(outputIsStdout bool) (string, error) {
lib.InternalCodingErrorIf(mv.mvtype != MT_STRING)
return colorizer.MaybeColorizeValue(millerJSONEncodeString(mv.printrep), outputIsStdout), nil
}
// Wraps with double-quotes and escape-encoded JSON-special characters.
func millerJSONEncodeString(input string) string {
var buffer bytes.Buffer
buffer.WriteByte('"')
for _, b := range []byte(input) {
switch b {
case '\\':
buffer.WriteByte('\\')
buffer.WriteByte('\\')
case '\n':
buffer.WriteByte('\\')
buffer.WriteByte('n')
case '\b':
buffer.WriteByte('\\')
buffer.WriteByte('b')
case '\f':
buffer.WriteByte('\\')
buffer.WriteByte('f')
case '\r':
buffer.WriteByte('\\')
buffer.WriteByte('r')
case '\t':
buffer.WriteByte('\\')
buffer.WriteByte('t')
case '"':
buffer.WriteByte('\\')
buffer.WriteByte('"')
default:
buffer.WriteByte(b)
}
}
buffer.WriteByte('"')
return buffer.String()
}
// ----------------------------------------------------------------
func (mv *Mlrval) marshalJSONInt(outputIsStdout bool) (string, error) {
lib.InternalCodingErrorIf(mv.mvtype != MT_INT)
return colorizer.MaybeColorizeValue(mv.String(), outputIsStdout), nil
}
// ----------------------------------------------------------------
func (mv *Mlrval) marshalJSONFloat(outputIsStdout bool) (string, error) {
lib.InternalCodingErrorIf(mv.mvtype != MT_FLOAT)
return colorizer.MaybeColorizeValue(mv.String(), outputIsStdout), nil
}
// ----------------------------------------------------------------
func (mv *Mlrval) marshalJSONBool(outputIsStdout bool) (string, error) {
lib.InternalCodingErrorIf(mv.mvtype != MT_BOOL)
return colorizer.MaybeColorizeValue(mv.String(), outputIsStdout), nil
}
// ----------------------------------------------------------------
func (mv *Mlrval) marshalJSONArray(
jsonFormatting TJSONFormatting,
elementNestingDepth int,
outputIsStdout bool,
) (string, error) {
lib.InternalCodingErrorIf(mv.mvtype != MT_ARRAY)
lib.InternalCodingErrorIf(jsonFormatting != JSON_SINGLE_LINE && jsonFormatting != JSON_MULTILINE)
// Put an array of all-terminal nodes all on one line, like '[1,2,3,4,5].
// TODO: libify
allTerminal := true
for _, element := range mv.arrayval {
if element.IsArrayOrMap() {
allTerminal = false
break
}
}
if allTerminal || (jsonFormatting == JSON_SINGLE_LINE) {
return mv.marshalJSONArraySingleLine(elementNestingDepth, outputIsStdout)
} else {
return mv.marshalJSONArrayMultipleLines(jsonFormatting, elementNestingDepth, outputIsStdout)
}
}
func (mv *Mlrval) marshalJSONArraySingleLine(
elementNestingDepth int,
outputIsStdout bool,
) (string, error) {
n := len(mv.arrayval)
var buffer bytes.Buffer
buffer.WriteByte('[')
for i, element := range mv.arrayval {
elementString, err := element.marshalJSONAux(JSON_SINGLE_LINE, elementNestingDepth+1, outputIsStdout)
if err != nil {
return "", err
}
buffer.WriteString(elementString)
if i < n-1 {
buffer.WriteString(", ")
}
}
buffer.WriteByte(']')
return buffer.String(), nil
}
// The element nesting depth is how deeply our element should be indented. Our
// closing bracket is indented one less than that. For example, a
// record '{"a":1,"b":[3,[4,5],6]"c":7}' should be formatted as
//
// {
// "a": 1,
// "b": [ <-- root-level map element nesting depth is 1
// 3, <-- this array's element nesting depth is 2
// [4, 5],
// 6
// ], <-- this array's closing-bracket is 1, one less than its element nesting detph
// "c": 7
// }
func (mv *Mlrval) marshalJSONArrayMultipleLines(
jsonFormatting TJSONFormatting,
elementNestingDepth int,
outputIsStdout bool,
) (string, error) {
n := len(mv.arrayval)
var buffer bytes.Buffer
// Write empty array as '[]'
buffer.WriteByte('[')
if n > 0 {
buffer.WriteByte('\n')
}
for i, element := range mv.arrayval {
elementString, err := element.marshalJSONAux(jsonFormatting, elementNestingDepth+1, outputIsStdout)
if err != nil {
return "", err
}
for i := 0; i < elementNestingDepth; i++ {
buffer.WriteString(JSON_INDENT_STRING)
}
buffer.WriteString(elementString)
if i < n-1 {
buffer.WriteString(",")
}
buffer.WriteString("\n")
}
// Write empty array as '[]'
if n > 0 {
for i := 0; i < elementNestingDepth-1; i++ {
buffer.WriteString(JSON_INDENT_STRING)
}
}
buffer.WriteByte(']')
return buffer.String(), nil
}
// ----------------------------------------------------------------
func (mv *Mlrval) marshalJSONMap(
jsonFormatting TJSONFormatting,
elementNestingDepth int,
outputIsStdout bool,
) (string, error) {
lib.InternalCodingErrorIf(mv.mvtype != MT_MAP)
s, err := mv.mapval.marshalJSONAux(jsonFormatting, elementNestingDepth, outputIsStdout)
if err != nil {
return "", err
}
return s, nil
}