-
Notifications
You must be signed in to change notification settings - Fork 0
/
EZstringify.safe.js
2743 lines (2417 loc) · 88.9 KB
/
EZstringify.safe.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
/*--------------------------------------------------------------------------------------------------
LINT options -- function below not called
--------------------------------------------------------------------------------------------------*/
/*global EZ, e:true */
var e;
(function jshint_globals_not_used() { //global variables and functions defined but not used
e = [e]
});
//EZ.stringify: 44, 45, 50, 53
EZ.json.options = {};
EZ.json.options.SPACES = 4;
//define default value as true if implicity enabled when all or script=true
//otherwise define as false if option must be explicitly specified
//options with numeric values set to 0 if -*all option specified
EZ.json.options.NAN = true;
EZ.json.options.INFINITY = true;
EZ.json.options.UNDEFINED = true;
EZ.json.options.REGEXP = true;
EZ.json.options.ARRAYKEYS = true;
EZ.json.options.ARRAYITEMSPERLINE = 10;
EZ.json.options.ARRAYMAXLINELENGTH = 80;
EZ.json.options.CIRCULAR = false;
EZ.json.options.FUNCTIONKEYS = true;
EZ.json.options.FUNCTIONSCRIPT = true;
EZ.json.options.FUNCTIONTYPE = false; //retain typeof function when FUNCTIONSCRIPT=false
//not sure of value
EZ.json.options.ROOT = '';
EZ.json.options.SCRIPT = false;
EZ.json.options.ALL = false;
/*---------------------------------------------------------------------------------------------
Diagnostic and research tool
---------------------------------------------------------------------------------------------*/
EZ.json.nodeLogger = function nodeLogger(key, value)
{
var log = EZ.json.log = EZ.json.log || [];
log.push(
'key=' + JSON.stringify(key).replace(/"/g,'')
+ '\t\t' +
'value=' + JSON.stringify(value) + '\n\t\t' +
JSON.stringify(this).replace(/"/g,'') // parent
);
return value;
}
/*---------------------------------------------------------------------------------------------
EZ.json.parse(value)
Extend navive JSON.parse to support extended json created by EZ.json.stringify()
ARGUMENTS:
value (String) json parsed to create Array(s), Object(s), RegExp(s) or Function(s)
(Object) create
---------------------------------------------------------------------------------------------*/
EZ.parse = function EZjson_parse(value)
{
var json, obj, pattern;
//----- if called with OBJECT (not String) . . .
// create named Array properties if any stored as last item of Array
// convert any pseudo function Objects to typeof 'function' Objects
if (value instanceof Object)
{
// use EZ.stringify() to create pseudo json then parse via eval()
json = EZ.stringify(value,'*script');
if (json != EZ.undefined) value = json;
return value; //return converted Object
}
//----- return value "as-is" if not String
if (typeof(value) != 'string') return value;
//----- if json prefixed with varible name, remove it (e.g. "varname = ...")
value = value.replace(/^\s*.*\s*=\s*/, '');
//----- if json contains function definitions, use EZ.json.parse()
if (/^\s*\(function\(\)/.test(value))
{
var obj = EZ.json.parse(value); //parse via eval()
return EZ.json.parse.message ? EZ.json.parse.message : obj;
}
//------------------------------------------------------------------
// parse json via JSON.parse() bt 1st escape unrecognized data types
// then un-escape via jsonExtendedParse() as each Object is created
//------------------------------------------------------------------
// global variables
var undefinedValueList = [], //Objects with undefined values
undefinedValueKeys = [], //Object keys containing undefined values
TAB = '@@tab@@',
NAN = '"@@NaN@@"',
UNDEFINED = '"@@undefined@@"',
REGEXP = '"@@RegExp@@',
FUNCTION = '"@@function@@',
functionPattern = /function(\s*(\w*)\s*\(([\s\S]*?)\)([^{]*){(\s*[\s\S]*?)})/;
/**********************************************************
* escape data types not recognized by native JSON.parse() *
**********************************************************/
value = value.replace(/\t/g, TAB);
//------------------------------------\\
//----- collapse multiline strings -----\\
//----------------------------------------\\
// e.g. ""
// + "John Tyler\n"
// + "President"
//
// --> "John Tyler\\nPresident"
//----------------------------------------//
value = value.replace(/(""\n\s*\+ "[\s\S]*?[^\\n]")(,?(\n|$))/g, function(all,str,eol)
{
str = str.replace(/""\s*\+ "/, '"'); //first line: "" + " --> "
str = str.replace(/\\n"\s*\+ "/g, '\\n'); //other lines: \\n" + " --> \\n
return str + eol;
});
//--------------------------------------------\\
//----- escape undefined, NaN and Infinity -----\\
//------------------------------------------------\\
// e.g. NaN --> "@@NaN@@" //
// undefined --> "@@undefined@@" //
//-----------------------------------------------//
value = value.replace(/(\b|^)(undefined|NaN)(\b|$)(?=[^"'])/g, '"@@$2@@"');
//-------------------------------------------\\
//----- escape RegExp("pattern", "flags") -----\\
//-----------------------------------------------\\
// e.g. new RegExp("...", "...") //
// --> "@@RegExp@@/...pattern.../gim" //
//---------------------------------------------//
pattern = /\b(new\s*)?RegExp\s*\((.*?")\s*\)/g;
value = value.replace(pattern, function(all,newPrefix,regex)
{
var args = regex.split(/\s*,\s*/);
if (!args.length || args.length > 2) return all;
return '"@@RegExp@@' + args[0].substring(1,args[0].length-1) + '/'
+ (args[1] ? args[1].substring(1,args[1].length-1) : '');
});
//--------------------------------------\\
//----- escape RegExp /pattern/flags -----\\
//------------------------------------------\\
// e.g. RegExp /.../gim //
// or new RegExp /.../gim //
// --> "@@RegExp@@/...pattern.../gim"//
//---------------------------------------//
value = value.replace(/(^|[\[\{\s,]*)\/(.*\/[gim]*)(?=($|[\]\}\s,]))/gim,
function(all,beg,regex)
{
return beg + '"@@RegExp@@' + regex.replace(/\\/g, '\\\\') + '"';
});
//--------------------------------------------\\
//----- escape function [name](args) {...} -----\\
//------------------------------------------------\\
// e,g. function mine(arg) { //
// return arg; //
// } //
// --> "@@function@@ myFunc(arg) {\\n...}"//
//--------------------------------------------//
// regex = /"____function____": "function(.*)"/g;
// value = value.replace(regex, '"@@function@@$1"');
//=======================================================================
try
{
EZ.json.eval = JSON.parse(value.trim(), jsonExtendedParse);
return EZ.json.eval;
}
catch (e)
{
value = value.replace(RegExp(TAB, 'g'), '\t');
EZ.json.parse(value);
return EZ.json.parse.message; //parse via eval()
}
//=======================================================================
//__________________________________________________________________________________________
/**
* callback function WORKHORSE -- called for children before parents
* processes: NaN, undefined, RegExp, Function -or- named Array properties
*/
function jsonExtendedParse(key, value)
{
var fn, idx, results;
switch (typeof value)
{
case 'string':
{
//--------------------\\
//----- pseudo tab -----\\
//------------------------\\
value = value.replace(RegExp(TAB, 'g'), '\t');
//-----------------------------------------\\
//----- pseudo NaN, undefined or RegExp -----\\
//---------------------------------------------\\
results = value.match(/^@@(.*?)@@(.*)/)
if (!results)
return value;
switch (results[1])
{
case 'NaN':
return NaN;
case 'undefined':
{
if (!key) return undefined; //return if value not Object property
if ((idx = undefinedValueList.indexOf(this)) == -1)
{
idx = undefinedValueList.push(this) - 1;
undefinedValueKeys[idx] = [];
}
undefinedValueKeys[idx].push(key); //undefined value must be set later
return null;
}
case 'RegExp':
{
results = results[2].match(RegExp("(.*)\\/(.*)",""));
if (!results)
return value;
return new RegExp(results[1], results[2]);
//return new RegExp(results[1].replace(/\\/g, '\\\\'), results[2]);
}
}
}
/* jshint ignore:start*/ //FALL-thru
case 'object':
/* jshint ignore:end */
{
//-------------------------------\\
//----- null -- no processing -----\\
//-----------------------------------\\
if (!value) return value;
//---------------------------------------\\
//----- set undefined property values -----\\
//-------------------------------------------\\
if ((idx = undefinedValueList.indexOf(value)) != -1)
{
while (undefinedValueKeys.length) //set undefined values
value[undefinedValueKeys.shift()] = undefined;
undefinedValueList.splice(idx,1); //delete Object from list
}
//-------------------------------------------\\
//----- Array -- process named properties -----\\
//-----------------------------------------------\\
if (value.constructor == Array)
{
if (!value.length) //bail if no Array items
return value;
var pseudoItem = value[value.length-1];
if (pseudoItem == null
|| typeof pseudoItem != 'object' //bail if NO named properties
|| ('____properties____' in pseudoItem) === false)
return value;
Object.keys(pseudoItem.____properties____).forEach(
function(key) //get named properties...
{ //...from pseudoItem Object
value[key] = pseudoItem.____properties____[key];
});
value.splice(value.length-1,1); //...then delete pseudoItem
return value;
}
//-------------------------------------------\\
//----- Function (or TODO: custom Object) -----\\
//-----------------------------------------------\\
if ('____function____' in value)
{
try
{ //create function
eval('fn = ' + value.____function____)
Object.keys(value).forEach(function(key)
{ //copy any enumerable properties
if (key != '____function____')
fn[key] = value[key];
});
value = fn; //return function
}
catch (e)
{
void(0); //debugger breakpoint
}
return value;
}
}
/* jshint ignore:start*/ //FALL-thru
default: return value;
/* jshint ignore:end */
}
}
}
//__________________________________________________________________________________________
/**
* EZ.json.parse(json,layer)
*
* parse json via eval -- if exception, eval json in fragments to isolate syntax error.
*
* ARGUMENTS:
* json String containing json
* layer html layer OR layer id used for error message
* TODO: for full backward compatible with original EASY.js
*
* RETURNS:
* EZ.json.parse.objname set to name of variable if json of the form: objname = ...
* otherwise blank
*
* with no exception:
* EZ.json.eval (and EZ.json.parse.objname variable) set to value from json and returned.
* EZ.json.parse.message blank
*
* with SyntaxError exception:
* EZ.json.eval set to null and returned -- EZ.json.parse.objname variable unchanged
* EZ.json.parse.message contains json fragments parsed sucessfully with message inserted
* before fragment with SyntaxError.
*
* FRAGMENTS:
* The outermost json Object or Function declaration and each nested Object/Function
* is considered as a fragment containing zero or more fragment items. Fragments
* items are either another fragment or non-object data type such as Boolean,
* Number or String. Statements within a Function declartions are treated as a
* fragment item -- except as noted below.
*
* Closure functions enclosed within paraenthesis take precedence as a fragment
* over the function definition.
*
* Closure functions used as argements of forEach, every, some or replace are
* treated as a complete fragment item of their containig function.
*
* Fragments are passed to eval as found in json first with no fragment items,
* then each item added one at a time until all items are added or an exception
* occures.
*/
EZ.json.parse = function(json /*,layer */)
{
EZ.json.eval = null;
EZ.json.parse.objname = '';
EZ.json.parse.message = '';
EZ.json.parse.fragments = '';
EZ.json.parse.details = true; //more detail on returned script error message
json = json || '';
json = json.trim();
json = json.replace(/\\r/g, '\r');
json = json.replace(/\r\n/g, '\n').replace(/\r/g, '\n');
if (!json) //json empty
return EZ.json.eval = '';
json = json.replace(/^\s*(.*)\s*=\s*/, function(all,objname)
{ //remove "objname = " prefix if any
EZ.json.parse.objname = objname;
return '';
});
//------------------------\\
//----- eval full json -----\\
//----------------------------\\
try
{
eval('EZ.json.eval = ' + json);
if (EZ.json.parse.objname)
eval('"' + EZ.json.parse.objname + '=' + EZ.json.eval + '"');
return EZ.json.eval;
}
catch (e)
{
EZ.json.parse.message = e.message;
}
if (''.matchPlus == EZ.undefined)
return EZ.json.parse.message;
//--------------------------------------------------------\\
//----- eval json in fragments to isolate syntax error -----\\
//------------------------------------------------------------\\
var idx,
msg = '',
script = '';
EZ.trace(json);
//----- create shadow json with quoted strings neutered (except Object keys)
var jsonShadow = json.replace(/(\\['"])/g, '@@'); //esc embedded quotes e.g. \" --> @@
jsonShadow = jsonShadow.replace(/(['"])(.*?)\1(\s*)(\:?)/g, //to facitate simple parsing:
function(all, quote, inner, spaces, colon) //replace all quoted strings
{ //with #...# e.g. "abc" --> "###"
if (colon) return all; //except Object keys
return quote + '@'.dup(inner.length) + quote + spaces;
});
//----- also neuter "forEach(function(...){...});" to avoid parsing as fragments
jsonShadow = jsonShadow.replace(/(forEach\()([\s\S]*?\}.*\n)/g, function(all,prefix,fn)
{
return prefix + '@'.dup(fn.length);
});
/*___________________________________________________________________________________
//
// SAMPLE JSON before pre-processing nueters quoted Strings and some anounmous
// functions to simplify parsing into fragments and fragment items.
//___________________________________________________________________________________
{
guess: 123,
fn: (function()
{
var ____properties____ = {
color: "green",
array: [1, 2, "red", true]
};
Object.keys(____properties____).forEach(function(key)
{____function____[key] = ____properties____[key]})
return ____function____;
})()
}
-------------------------------------------------------------------------------------------
OPEN FRAGMENT OFFSETS
-------------------------------------------------------------------------------------------
offsets: 0:[0,1], 1:[18,43], 2:[44,74], 3:[75,95]
[0]: {
[1]: .... fn:. (function() .... {
[2]: .... var. ____properties____. =. {
[3]: .[12]. array:. [
-------------------------------------------------------------------------------------------
CLOSE FRAGMENT OFFSETS
-------------------------------------------------------------------------------------------
offsets: 0:[75,100], 1:[101,111], 2:[265,273], 3:[274,275]
[0]: array: [1, 2]
[1]: };
[2]: })()
[3]:}
-------------------------------------------------------------------------------------------
// SAMPLE NUETERED DATA - embedded quotes and forEach converted to @ for parsing
// start of fragments marked as -->>...<-- end of fragments marked as --<<...<--
-------------------------------------------------------------------------------------------
__
| \................................fragment #0
| -->>
| {<--
| | guess: 123,
| |_________________________________openOffsets[0] = openResults.end[0] = 1
| ________
| | -->>\........................fragment #1
| | fn: (function()
| | {<--
| | |_____________________________openOffsets[1] = openResults.end[1] = 43
| | __________________________
| | | -->>\.....fragment #2
| | | var ____properties____ = {<--
| | | |____openOffsets[2] = openResults.end[2] = 74
| | |
| | | ________..............fragment #3
| | | | \ ___________openOffsets[3] = openResults.end[0] = 95
| | | | \ | _______closeOffsets[3] = closeResults.end[0] = 100 - 1 = 99
| | | | -->> <--|
| | | | array: [1, 2]
| | | | <<-- <-- end - marker size
| | | |_______________/
| | | __________________________closeOffsets[2] = (closeResults.end[1] = 111) - 2 = 109
| | | |
| | | <<--};<--
| | |_______/
| | Object.keys(____properties____).forEach@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
| | return ____function____;
| | <<--})()<--
| |________/
| |______________________________closeOffsets[1] = (closeResults.end[2] = 273) - 4 = 269
| <<--
| }<--
| |_________________________________closeOffsets[0] = (closeResults.end[3] = 275) - 1 = 274
|___/
*/
var begWrapPattern = RegExp( "(\\n\\s*)?" //prefix from line where marker starts
+ "(" //open marker -- if function...
+ "(\\(\\s*function||function)" //optional closure & fn statement
+ "\\s*[\\w]*\\([^(]*\\)" //optional fn name & (named args)
+ "[\\s\\S]*?\\{" //optional comment & start of body
+ "|\\{" //...or Object
+ "|\\[" //...or Array
+ ")" //end of open marker
+ "(\\s*?\\n?)", //optional spaces up to optional newline
"g");
var endWrapPattern = RegExp( "(.*)" //prefix from line where close marker starts
+ "(" //start of close marker
+ "\\}\\)\\(\\)" //end of optional closure -- TODO: expand
+ "|\\}|\\];?" //end of fn, object, array
+ ")" //end of close marker
+ "(\\s*?\\n*)", //optional spaces up to optional newline
"g");
var itemPatterns = {
"[": /(\s*)(())?(([^,]*)\s*)(,?\n?)/, //array -- value [,\n]
"{": /(\s*)(([^:]*)[:]\s*)(([^,]*)\s*)(,?\n?)/, //object -- key: value [,\n]
"(": /(\s*)(())((.*?);?)(\n?)$/m //function -- single lines .*[;]$
}
itemPatterns[')'] = itemPatterns['('];
var begWrappers =
{ //use for eval if defined
'{': 'EZ.obj={\n' //Object
}
var endWrappers = {
'[': ']', //Array
'{': '\n}', //Object
')': '\n}', //function...
'(': '\n})' //(function...)
}
//-----------------------------------------------\\
//----- find all start / end fragment markers -----\\
//---------------------------------------------------\\
var openTypes = [],
openOffsets = [],
closeOffsets = [],
openResults = jsonShadow.matchPlus(begWrapPattern),
closeResults = jsonShadow.matchPlus(endWrapPattern);
idx = 0;
jsonShadow.replace(begWrapPattern, function(all, prefix, marker, fn, eol)
{
var type = !fn ? marker
: marker.substr(0,1) == '(' ? '('
: ')';
var offset = openResults.end[idx] + eol.length - (eol ? 1 : 0);
openResults[idx++] = marker + eol;
openTypes.push(type);
openOffsets.push(offset);
});
idx = 0;
jsonShadow.replace(endWrapPattern, function(all,prefix,marker, eol)
{
closeResults[idx] = marker + eol; //?? prefix offsets may handle
closeOffsets.push(closeResults.end[idx] - marker.length - 1);
idx++;
});
//--------------------------------------------------------\\
//----- reorder closeOffsets to align with openOffsets -----\\
//------------------------------------------------------------\\
openOffsets.forEach(function(begOffset,idx)
{
var begOffset = openOffsets[idx];
var endOffset = jsonShadow.length;
for (var i=idx; i<closeOffsets.length; i++)
{
for (var j=i+1; j<openOffsets.length; j++)
{
if (openOffsets[j] > closeOffsets[i])
break;
}
if (j == i+1)
break;
}
if (i < closeOffsets.length)
{ //swap closeOffsets
endOffset = closeOffsets.splice(i,1)[0];
closeOffsets.splice(idx,0,endOffset);
var endWrap = closeResults.splice(i,1)[0];
closeResults.splice(idx,0,endWrap);
}
EZ.json.parse.fragments += '\n' + '-'.dup(50)
+ '\nfragment #' + (idx + 1)
+ ' offsets: [' + begOffset + ',' +endOffset + ']'
+ '\n' + '-'.dup(50)
+ '\n-->>' + openResults[idx].replace(/([\s\S*?])(\n)/, '$1<--$2')
+ jsonShadow.substring(begOffset, endOffset)
+ '<<--' + closeResults[idx] + '<--';
});
openResults.push(''); //fake for idx+1 references
openOffsets.push(jsonShadow.length);
EZ.trace('FRAGMENTS', EZ.json.parse.fragments.substr(1));
EZ.json.parse.details = false;
//------------------------------\\
//----- parse outer fragment -----\\
//----------------------------------\\
idx = 0;
var offset = 0;
jsonFragment();
if (!msg && json.substr(offset)) //any remaining json is unexpected
{
msg = 'following unexpected';
jsonAppend('=', '@@@error@@@', '@@@good@@@');
//script += '@@@error@@@' + json.substr(offset);
//offset += json.substr(offset).length;
}
if (msg) //add to exception from full json eval
{
EZ.json.parse.message += '\nmore detail below...'
//------------------------------\\
//----- format error message -----\\
//----------------------------------\\
if (msg.substr(-1) != '\n') msg += '\n';
script = script.replace(/([\s\S]*\n)?([\s\S]*)@@@error@@@([\s\S]*)@@@good@@@(.*)(\n?)/,
function(all, linesBeforeBad, codeBeforeBad, bad, codeAfterBad)
{
linesBeforeBad = linesBeforeBad || '';
var indent = Math.max(0,codeBeforeBad.length - 1);
var indentBad = Math.max(0,indent + bad.length - 1);
bad.replace(/[\s\S]*\n(.*)/, function(all, bad /*last line of bad*/)
{
indentBad = Math.max(0,bad.length - 1);
});
all = linesBeforeBad
+ (linesBeforeBad ? '='.dup(50) : '') // ~~~~~~~~~~~~~~~~~~~~~~
+ '\n...' + msg + '' // ...msg
+ '_'.dup(indent) + '\n' // _______
+ ' '.dup(indent) + '\\\n' // \
+ codeBeforeBad + bad + codeAfterBad // before bad...after
+ '\n' + '_'.dup(indentBad+1) + '/\n' // _____________/
+ '...end of json parse\n' // ...end of parse
+ '='.dup(50) + '\n'; // ~~~~~~~~~~~~~~~~~~~~~~
return all;
});
}
script += json.substr(offset);
EZ.trace('SCRIPT returned', script);
//=============================================================
EZ.json.parse.message = 'SyntaxError: ' + EZ.json.parse.message
+ '\n'
+ '-'.dup(50) + '\n'
+ script;
return null;
//=============================================================
//_______________________________________________________________________________
/**
* recursively called for each json fragment until SyntaxError occurs.
*/
function jsonFragment(depth/*lastBegWrap, lastEndWrap, lastType*/)
{
depth = depth || 0;
if (idx >= openOffsets.length) return; //no more fragment markers
var item,
begWrap = openResults[idx],
endWrap = closeResults[idx],
begOffset = openOffsets[idx],
endOffset = closeOffsets[idx],
type = openTypes[idx],
begWrapType = begWrappers[type] || begWrap,
endWrapType = endWrappers[type],
fragmentItems = '';
jsonAppend(begWrap, '-->>', '<--');
offset = begOffset;
fragmentItems = begWrapType; //reset fragmentItems
//--------------------------------\\
//----- for each fragment item -----\\
//------------------------------------\\
var thisFragment = '';
var itemPattern = itemPatterns[type];
var count = jsonShadow.matchPlus(/(function|\]|\})/g).length;
do
{
//_______________________________________________________________________________
//
// EXAMPLE: items marked as #>...#< -- item separators as ^...^
// keys (or closure variable assignments) marked as !...!
//_______________________________________________________________________________
/*
-->>{<--
#>!guess: !"neutered quotes@red@"<#,
#>!fn: !>>(function()
-->>{<--
#>!var ____properties____ = !-->>{<--#>!
color: !"red"<#^,
^#>!array: !-->>[<--#>1<#^, ^#>2<#--<<]<--
--<<};<--
#>Object.keys(____properties____).forEach@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@<#
#>return ____function____;<#
--<<})()<--<#
--<<}<--
*/
var nextFragment = openOffsets[idx+1] - openResults[idx+1].length;
thisFragment = jsonShadow.substring(offset, Math.min(nextFragment, endOffset));
if (!thisFragment.length)
break;
var groups = "prefix, keyGroup, key, valueGroup, value, itemSep";
var results = thisFragment.matchPlus(itemPattern, groups);
if (!results.isFound) break;
results.start.forEach(function(start,idx)
{ //get un-neutered json results
item = json.substr(offset+start, results[idx].length);
results.set(results.keys[idx], item);thisFragment
});
//fragmentItems += results.prefix;
jsonAppend(results.prefix, '#>');
if (!results.keyGroup && !results.valueGroup)
{
jsonAppend(results.itemSep, '^', '^');
continue;
}
try
{
item = results.keyGroup + results.valueGroup;
if (type != '[' && item.substr(0,1) == '}')
{ //end of function or object
jsonAppend(item);
break;
}
if (type == '[' && results.key)
msg = 'name unexpected';
else if (type == '{' && !results.key)
msg = 'name required';
else
{
if (type == '{') //process key for Object
{
item = results.key;
eval('"' + results.key.trim().trimPlus('"') + '"');
jsonAppend(results.keyGroup, '!', '!')
item = results.valueGroup;
}
if (offset + item.length >= nextFragment)
{ //value is next fragment e.g. [...] or {...}
jsonAppend(item); //append json up to nextFragment
idx++;
item = jsonFragment(depth+1);
if (msg) return;
fragmentItems += item; //append json returned from fragment(s)
EZ.trace('fragmentItems return depth='+ depth, fragmentItems + endWrapType);
}
else
{
item = results.valueGroup;
eval(fragmentItems + item + endWrapType);
jsonAppend(item) //append valueGroup
}
if (EZ.json.parse.details) script += '<#';
jsonAppend(results.itemSep, '^', '^');
}
if (EZ.json.parse.details) script += '<#';
}
catch (e) //SyntaxError
{
msg = e.message; //...set error message
console.log(e.stack.replace(/([\s\S]*?\))[\s\S]*/,'$1'))
item = item.trim();
}
if (!msg) continue;
// add message to script and break
var padding = Math.max(0,script.length - script.lastIndexOf('\n') - 1);
jsonAppend(item, '@@@error@@@', '@@@good@@@');
json.substr(offset).replace(/.*\n/, function(all)
{
jsonAppend(all);
return all;
})
break;
}
while (count-- > 0) //safety for unexpected endless loop
if (msg || thisFragment.trim()) return;
if (!endWrap)
{
msg = 'expected: ' + endWrapType;
jsonAppend('', '@@@error@@@', '@@@good@@@');
}
else //append end of fragment wrapper and
{ //replace begWrapType with real begWrap
jsonAppend(endWrap, '<<--', '<--');
var regex = RegExp(begWrapType.replace(/([\[{(])/g,'\\$1'));
return fragmentItems.replace(regex, begWrap);
}
//_______________________________________________________________________________
/**
* Append un-neutered json to script and fragmentItems from current offset
* corresponding to code (i.e. code.length). Annotate with prefix and suffix if
* specified and starts with "@@@" or EZ.json.parse.details is true.
*/
function jsonAppend(code, prefix, suffix)
{
code = code || '';
prefix = prefix || '';
suffix = suffix || '';
if (!EZ.json.parse.details && prefix.indexOf('@@@') !== 0)
prefix = suffix = '';
if (!code && !prefix && !suffix) return;
fragmentItems += code;
if (prefix == '<<--' || prefix == '-->>') //complex annotate
script += annotate(code, prefix, suffix);
else //simple annotate
script += prefix + json.substr(offset, code.length) + suffix;
offset += code.length;
EZ.trace('fragmentItems depth='+ depth, fragmentItems + endWrapType);
EZ.trace('SCRIPT: ' + code, script);
}
/**
* returns annotated fragment marker
*/
function annotate(code, prefix, suffix)
{
return code.replace(/(\s*)([\s\S]*?)(\n?)$/,
function(all,before,marker,after)
{
before = before.endsWith('\n') || !before.length ? prefix + '\n'
: before.substr(-4) + prefix
return before + marker + suffix + after;
});
}
}
}
/*---------------------------------------------------------------------------------------------
EZ.json.stringify(value, replacer, spaces)
DESCRIPTION:
-----------------------------
Support following data types:
-----------------------------
NaN, Infinity, undefined, RegExp
function (both script and enumerable properties)
non-alphanumeric Array properties
partial support for html Objects
json format options specify if and how above additional data types
are represented by json
native JSON.stringify() ignores or does not exactly reprentsent
these type e.g. NaN formatted as null
----------------------------
Additional replacer options:
----------------------------
allowes multiple replacer functions
blacklist of properties in addition to native whitelist
----------------------------------
Optional readibility improvements:
----------------------------------
individual Array items not intented -- formatted together on same line
(space added after comma separating items)
Multiline Strings formatted on multiple un-indented lines
Object property / keys only enclosed in quotes for invalid varible names
e.g. "*note" "*%$?"
-------------------
Other Enhancements:
-------------------
Objects repeated or with circular references are only formatted once
________________________________________________________________________________________
ARGUMENTS: same as JSON.stringify plus . . .
value (required) Array, Object or value to stringify
replacer (Function) same as native JSON.stringify()
specifies single REPLACER FUNCTION -- see below
(Array) same as native JSON.stringify() plus enhacements described below
An array of String and Number objects that serve as a whitelist for
selecting the properties of the value object to be included in the
JSON string. If this value is null or not specified all properties
of the object are included in the resulting JSON striing.
(String) space delimited EZ.stringify() json format options described below
of the following form:
"NaN=true undefined=false arrayItemsPerLine=10 include=id,name"
(Object) One or more EZ.stringify() json format options provided as key/value
sof the following EZ.stringify() options as described below:
----------------------
OBJECT PROPERTY NAMES:
----------------------
When any property name is specified, Object properties are formatted or ignored
based on the following rules:
***
no prefix only format specified names (whitelist) native JSON.stringify()
+ prefix always format property name in addition to whitelist names
- prefix do not format property name (blacklist) most precendence
-------------------
REPLACER FUNCTIONS:
-------------------
One or more functions called for each value, Array, Object or Function before
creating json. Each function called with the following arguments:
key property name or Array index of value -- blank for the root value
specified as 1st argument to EZ.stringify()
value root value or Object property value -- may be nested Object
this is the Object containing value i.e. this[key] === value
returned value is passed to the next replacer function or formatted as json
--------------------
JSON FORMAT OPTIONS:
--------------------
The following case-insensitive format options enable functionality if prefixed
with "+" or have no prefix -or- disabled if prefixed with "-"; options shown
with numeric values below are set to either specified value, zero if no value
specified and prefixed with minus "-" or default value for "+" prefix.
DEFAULTS: options shown with numeric values default to the value shown
all other options except *root and *script default to true if
*script enabled (true) or false if *script not enabled (false)
default for *script is false and *root must explicitly specified.
*all enabled or disabled all options e.g. "*all" or "-*all"
specific option(s) following take precedence
*NaN format as: NaN
if not specified formatted as: null
*Infinity format as: Infinity or -Infinity
if not specified formatted as: null
*undefined format as: undefined
if not specified formatted as: null
*RegExp format regular expressions as: /.../gim
if not specified formatted as: {}
*html format all attributes and non-false properties in addition
to any OBJECT PROPERTY NAMES specified
*arrayKeys named Array properties included by either embedding bit
of javascript if script option specified or by adding an
additional pseudo Array item with new Object containing
the named properties.
*arrayItemsPerLine=10 number of Array items shown on single line
value of 0, uses separate line for every item
*arrayMaxLineLength=80 maximum number of characters before using newline
for Array items not an Object, Array or multiline
String (always formatted on separate lines)
value of 0, uses separate line for every item
*functionKeys =true include enumerable function properties including
nested function and object properties formatted as
Object json if script option otherwise bit of javascript
embedded to recreate function Object type
=false enumerable properties ignored formats as: {}
*functionScript =true include full function script either as pseudo
pseudo Object property ____function____ or with bit of
embedded javascript to create function when json parsed
if script option specified
*functionType =true adds ____function____ property to Object json for
functions when *functionScript not enabled so function
is created by EZ.parse() -or- eval() if *script enabled
*root={objName} Specifies a root object variable name if specified,
prepended to returned json e.g.
objName = "...json..."
*script or * =true
creates pseudo json using embedded javascript to represent
some values such as function script or named Array properties
parsible with EZ.parse() or eval()
valid inside script tags or js file