/
json.js
executable file
·1756 lines (1669 loc) · 60.1 KB
/
json.js
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
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env node
/**
* Copyright 2020 Trent Mick.
* Copyright 2020 Joyent Inc.
*
* json -- JSON love for your command line.
*
* See <https://github.com/trentm/json> and <https://trentm.com/json/>
*/
var VERSION = '10.0.0';
var p = console.warn;
var util = require('util');
var assert = require('assert');
var path = require('path');
var vm = require('vm');
var fs = require('fs');
var warn = console.warn;
var EventEmitter = require('events').EventEmitter;
//--- exports for module usage
exports.main = main;
exports.getVersion = getVersion;
exports.parseLookup = parseLookup;
// As an exported API, these are still experimental:
exports.lookupDatum = lookupDatum;
exports.printDatum = printDatum; // DEPRECATED
//---- globals and constants
// Output modes.
var OM_JSONY = 1;
var OM_JSON = 2;
var OM_INSPECT = 3;
var OM_COMPACT = 4;
var OM_FROM_NAME = {
'jsony': OM_JSONY,
'json': OM_JSON,
'inspect': OM_INSPECT,
'compact': OM_COMPACT
};
//---- support functions
function getVersion() {
return VERSION;
}
/**
* Return a *shallow* copy of the given object.
*
* Only support objects that you get out of JSON, i.e. no functions.
*/
function objCopy(obj) {
var copy;
if (Array.isArray(obj)) {
copy = obj.slice();
} else if (typeof (obj) === 'object') {
copy = {};
Object.keys(obj).forEach(function (k) {
copy[k] = obj[k];
});
} else {
copy = obj; // immutable type
}
return copy;
}
if (util.format) {
format = util.format;
} else {
// From <https://github.com/joyent/node/blob/master/lib/util.js#L22>:
var formatRegExp = /%[sdj%]/g;
function format(f) {
var i;
if (typeof (f) !== 'string') {
var objects = [];
for (i = 0; i < arguments.length; i++) {
objects.push(util.inspect(arguments[i]));
}
return objects.join(' ');
}
i = 1;
var args = arguments;
var len = args.length;
var str = String(f).replace(formatRegExp, function (x) {
if (i >= len)
return x;
switch (x) {
case '%s':
return String(args[i++]);
case '%d':
return Number(args[i++]);
case '%j':
return JSON.stringify(args[i++]);
case '%%':
return '%';
default:
return x;
}
});
for (var x = args[i]; i < len; x = args[++i]) {
if (x === null || typeof (x) !== 'object') {
str += ' ' + x;
} else {
str += ' ' + util.inspect(x);
}
}
return str;
}
}
/**
* Parse the given string into a JS string. Basically: handle escapes.
*/
function _parseString(s) {
/* JSSTYLED */
var quoted = '"' + s.replace(/\\"/, '"').replace('"', '\\"') + '"';
return eval(quoted);
}
// json_parse.js (<https://github.com/douglascrockford/JSON-js>)
/* BEGIN JSSTYLED */
// START json_parse
var json_parse=function(){"use strict";var a,b,c={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:"\n",r:"\r",t:"\t"},d,e=function(b){throw{name:"SyntaxError",message:b,at:a,text:d}},f=function(c){return c&&c!==b&&e("Expected '"+c+"' instead of '"+b+"'"),b=d.charAt(a),a+=1,b},g=function(){var a,c="";b==="-"&&(c="-",f("-"));while(b>="0"&&b<="9")c+=b,f();if(b==="."){c+=".";while(f()&&b>="0"&&b<="9")c+=b}if(b==="e"||b==="E"){c+=b,f();if(b==="-"||b==="+")c+=b,f();while(b>="0"&&b<="9")c+=b,f()}a=+c;if(!isFinite(a))e("Bad number");else return a},h=function(){var a,d,g="",h;if(b==='"')while(f()){if(b==='"')return f(),g;if(b==="\\"){f();if(b==="u"){h=0;for(d=0;d<4;d+=1){a=parseInt(f(),16);if(!isFinite(a))break;h=h*16+a}g+=String.fromCharCode(h)}else if(typeof c[b]=="string")g+=c[b];else break}else g+=b}e("Bad string")},i=function(){while(b&&b<=" ")f()},j=function(){switch(b){case"t":return f("t"),f("r"),f("u"),f("e"),!0;case"f":return f("f"),f("a"),f("l"),f("s"),f("e"),!1;case"n":return f("n"),f("u"),f("l"),f("l"),null}e("Unexpected '"+b+"'")},k,l=function(){var a=[];if(b==="["){f("["),i();if(b==="]")return f("]"),a;while(b){a.push(k()),i();if(b==="]")return f("]"),a;f(","),i()}}e("Bad array")},m=function(){var a,c={};if(b==="{"){f("{"),i();if(b==="}")return f("}"),c;while(b){a=h(),i(),f(":"),Object.hasOwnProperty.call(c,a)&&e('Duplicate key "'+a+'"'),c[a]=k(),i();if(b==="}")return f("}"),c;f(","),i()}}e("Bad object")};return k=function(){i();switch(b){case"{":return m();case"[":return l();case'"':return h();case"-":return g();default:return b>="0"&&b<="9"?g():j()}},function(c,f){var g;return d=c,a=0,b=" ",g=k(),i(),b&&e("Syntax error"),typeof f=="function"?function h(a,b){var c,d,e=a[b];if(e&&typeof e=="object")for(c in e)Object.prototype.hasOwnProperty.call(e,c)&&(d=h(e,c),d!==undefined?e[c]=d:delete e[c]);return f.call(a,b,e)}({"":g},""):g}}();
// END json_parse
/* END JSSTYLED */
function printHelp() {
/* BEGIN JSSTYLED */
var w = console.log;
w('Usage:');
w(' <something generating JSON on stdout> | json [OPTIONS] [LOOKUPS...]');
w(' json -f FILE [OPTIONS] [LOOKUPS...]');
w('');
w('Pipe in your JSON for pretty-printing, JSON validation, filtering, ');
w('and modification. Supply one or more `LOOKUPS` to extract a ');
w('subset of the JSON. HTTP header blocks are skipped by default.');
w('Roughly in order of processing, features are:');
w('');
w('Grouping:');
w(' Use "-g" or "--group" to group adjacent objects, separated by');
w(' by no space or a by a newline, or adjacent arrays, separate by');
w(' by a newline. This can be helpful for, e.g.: ');
w(' $ cat *.json | json -g ... ');
w(' and similar.');
w('');
w('Execution:');
w(' Use the "-e CODE" option to execute JavaScript code on the input JSON.');
w(' $ echo \'{"name":"trent","age":38}\' | json -e \'this.age++\'');
w(' {');
w(' "name": "trent",');
w(' "age": 39');
w(' }');
w(' If input is an array, this will automatically process each');
w(' item separately.');
w('');
w('Conditional filtering:');
w(' Use the "-c CODE" option to filter the input JSON.');
w(' $ echo \'[{"age":38},{"age":4}]\' | json -c \'this.age>21\'');
w(' [{\'age\':38}]');
w(' If input is an array, this will automatically process each');
w(' item separately. Note: "CODE" is JavaScript code.');
w('');
w('Lookups:');
w(' Use lookup arguments to extract particular values:');
w(' $ echo \'{"name":"trent","age":38}\' | json name');
w(' trent');
w('');
w(' Use "-a" for *array processing* of lookups and *tabular output*:');
w(' $ echo \'{"name":"trent","age":38}\' | json name age');
w(' trent');
w(' 38');
w(' $ echo \'[{"name":"trent","age":38},');
w(' {"name":"ewan","age":4}]\' | json -a name age');
w(' trent 38');
w(' ewan 4');
w('');
w('In-place editing:');
w(' Use "-I, --in-place" to edit a file in place:');
w(' $ json -I -f config.json # reformat');
w(' $ json -I -f config.json -c \'this.logLevel="debug"\' # add field');
w('');
w('Pretty-printing:');
w(' Output is "jsony" by default: 2-space indented JSON, except a');
w(' single string value is printed without quotes.');
w(' $ echo \'{"name": "trent", "age": 38}\' | json');
w(' {');
w(' "name": "trent",');
w(' "age": 38');
w(' }');
w(' $ echo \'{"name": "trent", "age": 38}\' | json name');
w(' trent');
w('');
w(" Use '-j' or '-o json' for explicit JSON, '-o json-N' for N-space indent:");
w(' $ echo \'{"name": "trent", "age": 38}\' | json -o json-0');
w(' {"name":"trent","age":38}');
w('');
w('Options:');
w(' -h, --help Print this help info and exit.');
w(' --version Print version of this command and exit.');
w(' -q, --quiet Don\'t warn if input isn\'t valid JSON.');
w('');
w(' -f FILE Path to a file to process. If not given, then');
w(' stdin is used.');
w(' -I, --in-place In-place edit of the file given with "-f".');
w(' Lookups are not allow with in-place editing');
w(' because it makes it too easy to lose content.');
w('');
w(' -H Drop any HTTP header block (as from `curl -i ...`).');
w(' -g, --group Group adjacent objects or arrays into an array.');
w(' --merge Merge adjacent objects into one. Keys in last ');
w(' object win.');
w(' --deep-merge Same as "--merge", but will recurse into objects ');
w(' under the same key in both.')
w(' -a, --array Process input as an array of separate inputs');
w(' and output in tabular form.');
w(' -A Process input as a single object, i.e. stop');
w(' "-e" and "-c" automatically processing each');
w(' item of an input array.');
w(' -d DELIM Delimiter char for tabular output (default is " ").');
w(' -D DELIM Delimiter char between lookups (default is "."). E.g.:');
w(' $ echo \'{"a.b": {"b": 1}}\' | json -D / a.b/b');
w('');
w(' -M, --items Itemize an object into an array of ');
w(' {"key": <key>, "value": <value>}');
w(' objects for easier processing.');
w('');
w(' -e CODE Execute the given JavaScript code on the input. If input');
w(' is an array, then each item of the array is processed');
w(' separately (use "-A" to override).');
w(' -c CODE Filter the input with JavaScript `CODE`. If `CODE`');
w(' returns false-y, then the item is filtered out. If');
w(' input is an array, then each item of the array is ');
w(' processed separately (use "-A" to override).');
w('');
w(' -k, --keys Output the input object\'s keys.');
w(' -n, --validate Just validate the input (no processing or output).');
w(' Use with "-q" for silent validation (exit status).');
w('');
w(' -o, --output MODE');
w(' Specify an output mode. One of:');
w(' jsony (default): JSON with string quotes elided');
w(' json: JSON output, 2-space indent');
w(' json-N: JSON output, N-space indent, e.g. "json-4"');
w(' inspect: node.js `util.inspect` output');
w(' -i Shortcut for `-o inspect`');
w(' -j Shortcut for `-o json`');
w(' -0, -2, -4 Set indentation to the given value w/o setting MODE.');
w(' -0 => -o jsony-0');
w(' -4 => -o jsony-4');
w(' -j0 => -o json-0');
w('');
w('See <http://trentm.com/json> for more docs and ');
w('<https://github.com/trentm/json> for project details.');
/* END JSSTYLED */
}
/**
* Parse the command-line options and arguments into an object.
*
* {
* 'args': [...] // arguments
* 'help': true, // true if '-h' option given
* // etc.
* }
*
* @return {Object} The parsed options. `.args` is the argument list.
* @throws {Error} If there is an error parsing argv.
*/
function parseArgv(argv) {
var parsed = {
args: [],
help: false,
quiet: false,
dropHeaders: false,
exeSnippets: [],
condSnippets: [],
outputMode: OM_JSONY,
jsonIndent: 2,
array: null,
delim: ' ',
lookupDelim: '.',
items: false,
outputKeys: false,
group: false,
merge: null, // --merge -> 'shallow', --deep-merge -> 'deep'
inputFiles: [],
validate: false,
inPlace: false
};
// Turn '-iH' into '-i -H', except for argument-accepting options.
var args = argv.slice(2); // drop ['node', 'scriptname']
var newArgs = [];
var optTakesArg = {
'd': true,
'o': true,
'D': true
};
for (var i = 0; i < args.length; i++) {
if (args[i] === '--') {
newArgs = newArgs.concat(args.slice(i));
break;
}
if (args[i].charAt(0) === '-' && args[i].charAt(1) !== '-' &&
args[i].length > 2)
{
var splitOpts = args[i].slice(1).split('');
for (var j = 0; j < splitOpts.length; j++) {
newArgs.push('-' + splitOpts[j])
if (optTakesArg[splitOpts[j]]) {
var optArg = splitOpts.slice(j + 1).join('');
if (optArg.length) {
newArgs.push(optArg);
}
break;
}
}
} else {
newArgs.push(args[i]);
}
}
args = newArgs;
endOfOptions = false;
while (args.length > 0) {
var arg = args.shift();
if (endOfOptions) {
parsed.args.push(arg);
break;
}
switch (arg) {
case '--':
endOfOptions = true;
break;
case '-h': // display help and exit
case '--help':
parsed.help = true;
break;
case '--version':
parsed.version = true;
break;
case '-q':
case '--quiet':
parsed.quiet = true;
break;
case '-H': // drop any headers
parsed.dropHeaders = true;
break;
case '-o':
case '--output':
var name = args.shift();
if (!name) {
throw new Error('no argument given for "-o|--output" option');
}
var idx = name.lastIndexOf('-');
if (idx !== -1) {
var indent = name.slice(idx + 1);
if (/^\d+$/.test(indent)) {
parsed.jsonIndent = Number(indent);
name = name.slice(0, idx);
} else if (indent === 'tab') {
parsed.jsonIndent = '\t';
name = name.slice(0, idx);
}
}
parsed.outputMode = OM_FROM_NAME[name];
if (parsed.outputMode === undefined) {
throw new Error('unknown output mode: "' + name + '"');
}
break;
case '-0':
parsed.jsonIndent = 0;
break;
case '-2':
parsed.jsonIndent = 2;
break;
case '-4':
parsed.jsonIndent = 4;
break;
case '-I':
case '--in-place':
parsed.inPlace = true;
break;
case '-i': // output with util.inspect
parsed.outputMode = OM_INSPECT;
break;
case '-j': // output with JSON.stringify
parsed.outputMode = OM_JSON;
break;
case '-a':
case '--array':
parsed.array = true;
break;
case '-A':
parsed.array = false;
break;
case '-d':
parsed.delim = _parseString(args.shift());
break;
case '-D':
parsed.lookupDelim = args.shift();
if (parsed.lookupDelim.length !== 1) {
throw new Error(format(
'invalid lookup delim "%s" (must be a single char)',
parsed.lookupDelim));
}
break;
case '-e':
case '-E': // DEPRECATED in v9
parsed.exeSnippets.push(args.shift());
break;
case '-c':
case '-C': // DEPRECATED in v9
parsed.condSnippets.push(args.shift());
break;
case '-M':
case '--items':
parsed.items = true;
break;
case '-k':
case '--keys':
parsed.outputKeys = true;
break;
case '-g':
case '--group':
parsed.group = true;
break;
case '--merge':
parsed.merge = 'shallow';
break;
case '--deep-merge':
parsed.merge = 'deep';
break;
case '-f':
parsed.inputFiles.push(args.shift());
break;
case '-n':
case '--validate':
parsed.validate = true;
break;
default: // arguments
if (!endOfOptions && arg.length > 0 && arg[0] === '-') {
throw new Error('unknown option "' + arg + '"');
}
parsed.args.push(arg);
break;
}
}
if (parsed.group && parsed.merge) {
throw new Error('cannot use -g|--group and --merge options together');
}
if (parsed.outputKeys && parsed.args.length > 0) {
throw new Error(
'cannot use -k|--keys option and lookup arguments together');
}
if (parsed.inPlace && parsed.inputFiles.length !== 1) {
throw new Error('must specify exactly one file with "-f FILE" to ' +
'use -I/--in-place');
}
if (parsed.inPlace && parsed.args.length > 0) {
throw new Error('lookups cannot be specified with in-place editing ' +
'(-I/--in-place), too easy to lose content');
}
return parsed;
}
/**
* Streams chunks from given file paths or stdin.
*
* @param opts {Object} Parsed options.
* @returns {Object} An emitter that emits 'chunk', 'error', and 'end'.
* - `emit('chunk', chunk, [obj])` where chunk is a complete block of JSON
* ready to parse. If `obj` is provided, it is the already parsed
* JSON.
* - `emit('error', error)` when an underlying stream emits an error
* - `emit('end')` when all streams are done
*/
function chunkEmitter(opts) {
var emitter = new EventEmitter();
var streaming = true;
var chunks = [];
var leftover = '';
var finishedHeaders = false;
function stripHeaders(s) {
// Take off a leading HTTP header if any and pass it through.
while (true) {
if (s.slice(0, 5) === 'HTTP/') {
var index = s.indexOf('\r\n\r\n');
var sepLen = 4;
if (index == -1) {
index = s.indexOf('\n\n');
sepLen = 2;
}
if (index != -1) {
if (!opts.dropHeaders) {
emit(s.slice(0, index + sepLen));
}
var is100Continue = (
s.slice(0, 21) === 'HTTP/1.1 100 Continue');
s = s.slice(index + sepLen);
if (is100Continue) {
continue;
}
finishedHeaders = true;
}
} else {
finishedHeaders = true;
}
break;
}
//console.warn('stripHeaders done, finishedHeaders=%s', finishedHeaders)
return s;
}
function emitChunks(block, emitter) {
//console.warn('emitChunks start: block="%s"', block)
/* JSSTYLED */
var splitter = /(})(\s*\n\s*)?({\s*")/;
var leftTrimmedBlock = block.trimLeft();
if (leftTrimmedBlock && leftTrimmedBlock[0] !== '{') {
// Currently only support streaming consecutive *objects*.
streaming = false;
chunks.push(block);
return '';
}
/**
* Example:
* > '{"a":"b"}\n{"a":"b"}\n{"a":"b"}'.split(/(})(\s*\n\s*)?({\s*")/)
* [ '{"a":"b"',
* '}',
* '\n',
* '{"',
* 'a":"b"',
* '}',
* '\n',
* '{"',
* 'a":"b"}' ]
*/
var bits = block.split(splitter);
//console.warn('emitChunks: bits (length %d): %j', bits.length, bits);
if (bits.length === 1) {
/*
* An unwanted side-effect of using a regex to find
* newline-separated objects *with a regex*, is that we are looking
* for the end of one object leading into the start of a another.
* That means that we can end up buffering a complete object until
* a subsequent one comes in. If the input stream has large delays
* between objects, then this is unwanted buffering.
*
* One solution would be full stream parsing of objects a la
* <https://github.com/creationix/jsonparse>. This would nicely
* also remove the artibrary requirement that the input stream be
* newline separated. jsonparse apparently has some issues tho, so
* I don't want to use it right now. It also isn't *small* so not
* sure I want to inline it (`json` doesn't have external deps).
*
* An alternative: The block we have so far one of:
* 1. some JSON that we don't support grouping (e.g. a stream of
* non-objects),
* 2. a JSON object fragment, or
* 3. a complete JSON object (with a possible trailing '{')
*
* If #3, then we can just emit this as a chunk right now.
*
* TODO(PERF): Try out avoiding the first more complete regex split
* for a presumed common case of single-line newline-separated JSON
* objects (e.g. a bunyan log).
*/
// An object must end with '}'. This is an early out to avoid
// `JSON.parse` which I'm *presuming* is slower.
var trimmed = block.split(/\s*\r?\n/)[0];
if (trimmed[trimmed.length - 1] === '}') {
var obj;
try {
obj = JSON.parse(block);
} catch (e) {
/* pass through */
}
if (obj !== undefined) {
// Emit the parsed `obj` to avoid re-parsing it later.
emitter.emit('chunk', block, obj);
block = '';
}
}
return block;
} else {
var n = bits.length - 2;
var s;
s = bits[0] + bits[1];
emitter.emit('chunk', s, JSON.parse(s));
for (var i = 3; i < n; i += 4) {
s = bits[i] + bits[i + 1] + bits[i + 2];
emitter.emit('chunk', s, JSON.parse(s));
}
return bits[n] + bits[n + 1];
}
}
function addDataListener(stream) {
stream.on('data', function (chunk) {
var s = leftover + chunk;
if (!finishedHeaders) {
s = stripHeaders(s);
}
if (!finishedHeaders) {
leftover = s;
} else {
if (!streaming) {
chunks.push(chunk);
return;
}
if (chunk.lastIndexOf('\n') >= 0) {
leftover = emitChunks(s, emitter);
} else {
leftover = s;
}
}
});
}
if (opts.inputFiles.length > 0) {
// Stream each file in order.
var i = 0;
function addErrorListener(file) {
file.on('error', function (err) {
emitter.emit(
'error',
format('could not read "%s": %s', opts.inputFiles[i], e)
);
});
}
function addEndListener(file) {
file.on('end', function () {
if (i < opts.inputFiles.length) {
var next = opts.inputFiles[i++];
var nextFile = fs.createReadStream(next,
{encoding: 'utf8'});
addErrorListener(nextFile);
addEndListener(nextFile);
addDataListener(nextFile);
} else {
if (!streaming) {
emitter.emit('chunk', chunks.join(''));
} else if (leftover) {
leftover = emitChunks(leftover, emitter);
emitter.emit('chunk', leftover);
}
emitter.emit('end');
}
});
}
var first = fs.createReadStream(opts.inputFiles[i++],
{encoding: 'utf8'});
addErrorListener(first);
addEndListener(first);
addDataListener(first);
} else {
// Streaming from stdin.
var stdin = process.openStdin();
stdin.setEncoding('utf8');
addDataListener(stdin);
stdin.on('end', function () {
if (!streaming) {
emitter.emit('chunk', chunks.join(''));
} else if (leftover) {
leftover = emitChunks(leftover, emitter);
emitter.emit('chunk', leftover);
}
emitter.emit('end');
});
}
return emitter;
}
/**
* Get input from either given file paths or stdin. If `opts.inPlace` then
* this calls the callback once for each `opts.inputFiles`.
*
* @param opts {Object} Parsed options.
* @param callback {Function} `function (err, content, filename)` where err
* is an error string if there was a problem, `content` is the read
* content and `filename` is the associated file name from which content
* was loaded if applicable.
*/
function getInput(opts, callback) {
if (opts.inputFiles.length === 0) {
// Read from stdin.
var chunks = [];
var stdin = process.openStdin();
stdin.setEncoding('utf8');
stdin.on('data', function (chunk) {
chunks.push(chunk);
});
stdin.on('end', function () {
callback(null, chunks.join(''));
});
} else if (opts.inPlace) {
for (var i = 0; i < opts.inputFiles.length; i++) {
var file = opts.inputFiles[i];
var content;
try {
content = fs.readFileSync(file, 'utf8');
} catch (e) {
callback(e, null, file);
}
if (content) {
callback(null, content, file);
}
}
} else {
// Read input files.
var i = 0;
var chunks = [];
try {
for (; i < opts.inputFiles.length; i++) {
chunks.push(fs.readFileSync(opts.inputFiles[i], 'utf8'));
}
} catch (e) {
return callback(
format('could not read "%s": %s', opts.inputFiles[i], e));
}
callback(null, chunks.join(''),
(opts.inputFiles.length === 1 ? opts.inputFiles[0] : undefined));
}
}
function isInteger(s) {
return (s.search(/^-?[0-9]+$/) == 0);
}
/**
* Parse a lookup string into a list of lookup bits. E.g.:
*
* 'a.b.c' -> ["a","b","c"]
* 'b["a"]' -> ["b","a"]
*
* Note: v10 made a backward incompatible change here that limits the supported
* *bracketed* lookups. A bracketed section of a lookup must be of one of the
* following forms:
* ["..."]
* ['...']
* [`...`]
* The quoted string is not evaluated, other than supporting a subset of JS
* string escapes (e.g. \', \", \n; but not unicode char escapes).
* See the long block comment below in this function for details.
*
* Optionally receives an alternative lookup delimiter (other than '.')
*/
function parseLookup(lookup, lookupDelim) {
var debug = function () {};
// var debug = console.warn;
var bits = [];
debug('\n*** ' + lookup + ' ***');
bits = [];
lookupDelim = lookupDelim || '.';
var bit = '';
var states = [null];
var escaped = false;
var ch = null;
for (var i = 0; i < lookup.length; ++i) {
var ch = lookup[i];
debug('-- i=' + i + ', ch=' + JSON.stringify(ch) + ' escaped=' +
JSON.stringify(escaped));
debug('states: ' + JSON.stringify(states));
// Handle a *limited subset* of JS string escapes.
// JSSTYLED
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#Escape_notation
var SUPPORTED_ESCAPES = {
'\'': '\'',
'\"': '\"',
'\`': '\`',
'\\': '\\',
'n': '\n',
'r': '\r',
't': '\t',
'v': '\v',
'b': '\b',
'f': '\f'
};
if (ch === '\\' && i+1 < lookup.length) {
var nextCh = lookup[i+1];
var escapedCh = SUPPORTED_ESCAPES[nextCh];
if (escapedCh !== undefined) {
debug('escaped: %j -> %j', ch+nextCh, escapedCh);
bit += escapedCh;
i++;
continue;
}
}
switch (states[states.length - 1]) {
case null:
switch (ch) {
case '"':
case '\'':
states.push(ch);
bit += ch;
break;
case '[':
states.push(ch);
if (bit !== '') {
bits.push(bit);
bit = ''
}
bit += ch;
break;
case lookupDelim:
if (bit !== '') {
bits.push(bit);
bit = ''
}
break;
default:
bit += ch;
break;
}
break;
case '[':
bit += ch;
switch (ch) {
case '"':
case '\'':
case '[':
states.push(ch);
break;
case ']':
states.pop();
if (states[states.length - 1] === null) {
// `bit` is a bracketed string, `[...]`.
//
// The *intent* is to allow specifying an object key
// that would otherwise get interpreted by `json`s
// LOOKUP parsing -- typically if the key has a `.` in it.
//
// Up to and including json v9, this was handled by eval'ing
// the given string inside the brackets (via
// `vm.runInNewContext`). However, trentm/json#144 shows
// that this is an avenue for command injection. It was
// never made clear in `json` documentation that one
// should never use user-provided strings for LOOKUPs, so
// we should close this vulnerability.
//
// Expected usage and documented examples are like this:
// ["foo.bar"]
// ['foo.bar']
// However, older implementation of eval'ing meant that
// things like the following worked:
// [42]
// ["my" + "key"]
// [(function () { return "mykey" })()]
//
// The documentation was never explicit about denying
// expressions would work. v10 **breaks compatibility**
// to only support a bracketed string:
// ["..."]
// ['...']
// [`...`] # note: no var interpolation is done
// and error otherwise.
var VALID_QUOTES = '"\'`';
var sQuote = bit[1];
var eQuote = bit.slice(-2, -1);
if (VALID_QUOTES.indexOf(sQuote) === -1 ||
sQuote !== eQuote)
{
throw new Error(format('invalid bracketed lookup ' +
'string: %j (must be of the form [\'...\'], ' +
'["..."], or [`...`])', bit));
}
bits.push(bit.slice(2, -2));
bit = ''
}
break;
}
break;
case '"':
bit += ch;
switch (ch) {
case '"':
states.pop();
if (states[states.length - 1] === null) {
bits.push(bit);
bit = ''
}
break;
}
break;
case '\'':
bit += ch;
switch (ch) {
case '\'':
states.pop();
if (states[states.length - 1] === null) {
bits.push(bit);
bit = ''
}
break;
}
break;
}
debug('bit: ' + JSON.stringify(bit));
debug('bits: ' + JSON.stringify(bits));
}
if (bit !== '') {
bits.push(bit);
bit = ''
}
// Negative-intify: strings that are negative ints we change to a Number for
// special handling in `lookupDatum`: Python-style negative array indexing.
var negIntPat = /^-\d+$/;
for (var i = 0; i < bits.length; i++) {
if (negIntPat.test(bits[i])) {
bits[i] = Number(bits[i]);
}
}
debug(JSON.stringify(lookup) + ' -> ' + JSON.stringify(bits));
return bits
}
/**
* Parse the given stdin input into:
* {
* 'error': ... error object if there was an error ...,
* 'datum': ... parsed object if content was JSON ...
* }
*
* @param buffer {String} The text to parse as JSON.
* @param obj {Object} Optional. Set when in streaming mode to avoid
* re-interpretation of `group`. Also avoids reparsing.
* @param group {Boolean} Default false. If true, then non-JSON input
* will be attempted to be 'arrayified' (see inline comment).
* @param merge {Boolean} Default null. Can be 'shallow' or 'deep'. An
* attempt will be made to interpret the input as adjacent objects to
* be merged, last key wins. See inline comment for limitations.
*/
function parseInput(buffer, obj, group, merge) {
if (obj) {
return {
datum: obj
};
} else if (group) {
/**
* Special case: Grouping (previously called auto-arrayification)
* of unjoined list of objects:
* {"one": 1}{"two": 2}
* and auto-concatenation of unjoined list of arrays:
* ["a", "b"]["c", "d"]
*
* This can be nice to process a stream of JSON objects generated from
* multiple calls to another tool or `cat *.json | json`.
*
* Rules:
* - Only JS objects and arrays. Don't see strong need for basic
* JS types right now and this limitation simplifies.
* - The break between JS objects has to include a newline:
* {"one": 1}
* {"two": 2}
* or no spaces at all:
* {"one": 1}{"two": 2}
* I.e., not this:
* {"one": 1} {"two": 2}
* This condition should be fine for typical use cases and ensures
* no false matches inside JS strings.
* - The break between JS *arrays* has to include a newline:
* ["one", "two"]
* ["three"]
* The 'no spaces' case is NOT supported for JS arrays as of v6.0.0