-
Notifications
You must be signed in to change notification settings - Fork 0
/
EZjsonPlus.js
2799 lines (2486 loc) · 88.3 KB
/
EZjsonPlus.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
/*--------------------------------------------------------------------------------------------------
Dreamweaver LINT global references and definitions not used here
--------------------------------------------------------------------------------------------------*/
/*global
EZ, DWfile,
e:true, g:true, dw:true, f:true
*/
var e; //global var for try/catch
(function() {[ //global variables and functions defined but not used
e, f, g, dw, DWfile ]});
//__________________________________________________________________________________________________
/*--------------------------------------------------------------------------------------------------
JSON.plus(o, options)
String.formatStack(options)
whats up...
ARGUMENTS:
String ...
options (optional) Object containing one or more of the following properties:
Array or delimited string (values separated by commas or spaces)
RETURNS:
true if ... otherwise ...
REFEERENCE:
TODO:
format: { //TODO: beta features not implemented - don't think we want
arrayItemsPerLine: 1,
arrayMaxlineLength: 80,
multilineStrings: 'break' //probably want this
},
--------------------------------------------------------------------------------------------------*/
EZ.jsonPlus = (function _____EZjsonPlus_____()
{
var options = EZ.defaultOptions.jsonPlus = {
monitor: true,
script: false, //add script to json to reset escaped values when parsed by eval()
circular: false, /* "native" throws exception if circular structures found
"delete" (or false) circular structures deleted
"escape" (or true) circular structures escaped
*/
repeated:'circular', /* currently hardcoded to treat same as circular
TODO: may want options to treat diff from circular
*/
alertLists: [], /* JSON reported as invalid if any of specified list not empty
-OR- list not empty and not included in infoLists below:
*/
infoLists: [ //information lists only -- unless specified in alertList
'escaped_values',
'excluded_values',
'ignored_constructors',
'html_elements',
'functions',
'deleted_functions'
],
escapeList: [], //internal -- ignore with include items removed
ignore: [
//'circular', //circular structured are deleted if specified -- otherwise escaped
//'repeated', //repeated Objects are stringified as separate equal Object
// otherwise they are escaped if not specified
// add "repeated" to exclude list to omit from json
'script', //script: only keep functions with enumerable properties
// and only keep the enumerable properties
//'function', //functions stringified as empty Object -- i.e. native behavior
// add "Function" to exclude list to omit from json
'constructor', //constructor all Objects and Functions cloned as Objects
// not original constructor -- does not apply to:
// Date, RegExp, Element or native functions.
// Does apply to NodeList or HTMLCollection ??
//Date, RegExp, html, NodeList, HTMLCollection
],
exclude: [], //dotName if starts with "." otherwise key or native function name
/*
e.g. Array, Date, RegExp, Element, Function ("native" for all)
Keys or native functions excluded from all Objects and Functions.
Function with enumerable properties NOT excluded if ignore
script also specified.
*/
include: [ //overrides items in exclude and ignore lists
],
html: { //EZ.format.Element options used to convert Element to Object
maxdepth: 4,
children: true,
extract:'all',
format:'object', //must be "object" to escape otherwise value changed
formatter:'none',
cloneNode: false,
ownerKeys: false,
boundFunctions: false, //TODO:
eventFunctions: false, //TODO:
exclude: [] //list of selectors excluded TODO:
},
console: '',
validate: false, //=true validate json reproduces Object
//creates validate_details if differences
validateEqualsOptions: {
showDiff:25,
html: true
},
clone: false, //returns clone using json -- implies validate
//="keep" returns json but rtnValue contains clone from json
unquoteKeys: false,
spaces: 4,
format: {
html: {extract:'all', format:'object', formatter:'none'}
},
safe: true, //=true clone input Object before escaping Function or Array
//TODO:
//=false to escape Function or Array w/o cloning Original
// (original Object is changed)
//="backup" clone input Object as backup (test convenience)
//="json" clone via json if clone needed otherwise uses cloneObject
replacer: null,
escapeTypes: [
'undefined',
'NaN', //escaped as Strings
'RegExp', 'Date',
'Array', //named keys / properties appended to Array as escaped Object
'Element',
'Function', //converted to Object of owner properties including inner functions
'circular',
'repeated', //TODO:
'script', //escape: fn name and script as escaped property
'function',
'constructor'
],
escapeMarker: 'JSON_escapeMarker', //wrapped with "@"
escapeHTML: '@HTML@',
escapePrefix: 'JSON.plus._temp=', //used as-is
escapeSuffix: 'JSON.plus.unescape(JSON.plus._temp);', //prefixed with semi-colon ";"
defaults: {
optionGroups: {
escapeAll: //TODO: nested optionGroups??
{
escape: 'Undefined NaN Date RegExp Array Element Function Script'.split(/\s+/)
},
basic: { //NOT escaping: Array, Element, Function or Object constructors
validate:true, unquoteKeys:true, circular:true,
escape: 'Undefined NaN Date RegExp'.split(/\s+/),
info: 'ignored_constructors'
},
cloning: {
validate:true, circular:true,
escape: 'Undefined NaN Date RegExp Array Element Function Script'.split(/\s+/),
ignore: 'none',
clone: true
},
save: {
validate:true, unquoteKeys:true, circular:true,
//include: 'circular Undefined NaN Date RegExp Array Element Function'.split(/\s+/),
ignore: ['constructor', 'script']
}
}
},
version: '11-25-2016'
}
//__________________________________________________________________________________________________
/**
* creates static / global instance -- set default JSON.plus options
*/
var _init = function _init()
{
var fn = new EZjsonPlus();
for (var key in fn)
EZjsonPlus[key] = fn[key];
JSON.plus = EZjsonPlus;
JSON.plus._callCount = 0;
EZjsonPlus.options = EZjsonPlus._options = options;
return EZjsonPlus;
}
//__________________________________________________________________________________________________
/**
* constructor (or JSON.plus.stringify() shortcut)
*/
function EZjsonPlus(obj, options)
{
if ( !(this instanceof arguments.callee)) //NOT called as constructor...
{
//return new EZ.jsonPlus(options);
return EZ.jsonPlus.stringify.apply(EZ.jsonPlus, [].slice.call(arguments));
}
if (EZ.jsonPlus) //if not called by _init()
{ //default options for this instance
options = obj;
options = this._options = EZ.options.call(EZ.jsonPlus.options, options);
options.rtnValue = new EZ.jsonPlus.rtnValue();
for (var fn in EZjsonPlus.prototype)
this[fn] = EZjsonPlus.prototype[fn];
}
else //bind global rtnValue functions to JSON.plus instance
{
}
}
/*--------------------------------------------------------------------------------------------------
JSON.plus.stringify(value, replacer, spaces)
--------------------------------------------------------------------------------------------------*/
EZjsonPlus.prototype.stringify = function EZjsonPlus_stringify(value, replacer, spaces)
{
var rtnValue = new EZ.rtnValue(true); //init rtnValue Object
var rtnData = rtnValue.getData();
var isTestFunction = EZ.test.isTestFunction();
if (isTestFunction)
void(0);
//if (isTestFunction) debugger;
JSON.plus._callCount++;
var msg = '';
var options = {};
switch (EZ.getType(replacer)) //check replacer
{
case 'Null':
case 'Undefined':
break;
case 'Function': //valid replacer
break;
case 'Array':
{
options.extract = replacer;
replacer = null;
break;
}
case 'Object': //Object is JSON.plus() options
{
options = replacer;
replacer = null;
break;
}
case 'Number':
case 'String': //use as spaces argument
{
if (arguments.length == 2)
{
options.spaces = replacer;
replacer = null;
break;
}
} //FALL-thru if not only 2 args
/* jshint ignore:start*/
default:
/* jshint ignore:end */
{ //ignore invalid replacer
replacer = null;
msg = 'invalid replacer argument ignored: ' + replacer;
}
}
rtnValue.addMessage(msg);
//-----------------------------------------------------
options = EZ.options.call(EZ.jsonPlus.options, options);
//-----------------------------------------------------
options.spaces = (arguments.length > 2) ? spaces : options.spaces;
options.replacer = replacer;
options.isTestFunction = isTestFunction
JSON.plus.stringify.rtnValue = rtnValue; //backward comptibility / convenience hack NOT
//...reliable in debugger if other threads run
delete options.defaults;
options.ignore = EZ.toArray(options.ignore, ', ')
options.include = EZ.toArray(options.include, ', ')
options.exclude = EZ.toArray(options.exclude, ', ')
options.extract = EZ.toArray(options.extract, ', ')
options.ignore.push('constructor'); //TODO: allow escape
var json = ''; //-----------------------------\\
try //----- finally create json -----\\
{ //---------------------------------\\
if (options.monitor)
replacer = JSON.plus.circularMonitor(options, rtnValue);
//=====================================================================================
json = rtnData.json = JSON.stringify(value, replacer, options.spaces);
//=====================================================================================
rtnData.json = json;
rtnValue.setOk(); //ok until found diff
//--------------------------------------------------------------------------------------
if (options.validate || options.clone) //validate if requested -- setFail() if bad
JSON.plus.validate.call(this, (rtnData.value || value), json, options, rtnValue);
//--------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------
if (options.unquoteKeys)
json = JSON.plus.unquoteKeys(json);
//--------------------------------------------------------------------------------------
for (var listName in rtnData.lists) //---------------------------------------\\
{ //----- build alert and info messages -----\\
var list = rtnData.lists[listName]; //-------------------------------------------\\
var count = (list instanceof Array) ? list.length
: Object.keys(list).length;
if (!options.alertLists.includes(listName)
&& (options.infoLists.includes('all') || options.infoLists.includes(listName)))
rtnValue.addInfo( EZ.s('# ' + listName, count) );
else
{
rtnValue.setFail();
rtnValue.addMessage( EZ.s('# ' + listName, count) );
}
}
if (typeof(json) == 'string' && options.script && rtnValue.haveList('escaped_values'))
json = options.escapePrefix + json + ';' + options.escapeSuffix;
}
catch (e) //most likely caused by circular Object
{ //...returns pseudo json below
if (e instanceof Error)
{ //message and stacktrace w/o message
rtnValue.addMessage(e.message);
rtnValue.addDetails(e.format());
}
else
{
rtnValue.addMessage(e + '');
rtnValue.addDetails(EZ.getStackTrace());
}
}
if (json || json === undefined) //return json if created -- otherwise...
{
//======================================================
return (options.clone === true) ? rtnData.clone
// : (options.rtnValue) ? rtnValue
: json;
//======================================================
}
if (!rtnValue.getMessageString()) //if no json and no message
{
EZ.oops('EZ.stringify() failed (reason unknown)');
rtnValue.addMessage(EZ.oops.message);
rtnValue.addDetails(EZ.oops.stackTrace);
}
//if no json, return message in json format
json = rtnValue.getMessage().concat(rtnValue.getDetails()).join('\n').trim();
json = json.wrap('"'); //format based on stringified value type
json = EZ.isArray(value) ? json.wrap('[]') //...Array: [...]
: (value instanceof Object) ? '{"": ' + json + '}' //...Object: {"", "...")
: json; //...String as is: "..."
// rtnData.message = (rtnData.message.length === 0) ? '' : rtnData.message.join('\n');
return json;
}
/*--------------------------------------------------------------------------------------------------
JSON stringify circular monitor -- originally created to gracefully handle circular structures.
Optionally escapes or deletes circular and repeated Objects as well as most Object types not fully
supported by native JSON.stringify() -- e.g. Dates, RegExp, Functions html Elements and more...
--------------------------------------------------------------------------------------------------*/
EZjsonPlus.prototype.circularMonitor = function EZjsonPlus_circularMonitor(options, rtnValue)
{
//var rtnValue = options.rtnValue;
var rtnData = rtnValue.getData();
var depth = 0, //_circular_monitor() global variables
depthKeys = [],
dotName = ['$'],
processedObj = [],
processedKey = rtnData.objectList = [],
marker = options.escapeMarker.wrap('@'),
replacer = options.replacer,
_checkEscape = this.escape; //reference to JSON.plus.escape()
//______________________________________________________________________________________________
/**
* closure function passed to JSON.stringify as replacer fn -- with access to above variables.
*/
function _circular_monitor(key, value)
{
if (rtnData.safe === false)
return undefined;
if (replacer) //caller specified replacer -- TODO: test
value = replacer.call(this, key, value);
delete options.repeatKey;
var replaceValue = null;
var ourKey = depth === 0 ? [] : [key];
var ourDotName = dotName.concat(ourKey).join('.')
options.dotName = ourDotName;
var obj = this[key];
var valueType = EZ.getType(obj, 'NaN Element');
//console.log({ key:key, dotName:ourDotName, type:valueType, value:value });
var d=ourDotName;
var dd = d;
void(d,dd);
if (value instanceof Object)
{
var keys = Object.keys(value);
if (value instanceof Array)
{
keys = Object.keys(value).join(',').match(/\d+/g) || [];
}
var processedIdx = processedObj.indexOf(value);
if (processedIdx == -1) //-----------------------------\\
{ //----- NOT repeated Object -----\\
processedObj.push(value); //---------------------------------\\
processedKey.push(ourDotName);
//must escape some types here
replaceValue = _checkEscape(value, options, rtnValue); //...Array, Element, Function, RegExp
if (replaceValue === null) //not escaped
void(0);
else if (valueType == 'Array') //Array with named properties
keys.push(obj.length); //add key with named properties
else if (replaceValue === undefined) // ??
return undefined; //deleted Object
//must replace this[key] for Function, Element
else if (replaceValue instanceof Object)
value = replaceValue;
else //replaceValue NOT Object (usually String)
{ //...replaceValue formatted below
key = (valueType == 'Array') ? 0 : marker;
keys = [key] // ?????????
}
}
//----------------------------\\
else //----- IS repeated Object -----\\
{ //--------------------------------\\
options.repeatKey = processedKey[processedIdx];
replaceValue = _checkEscape(value, options, rtnValue);
if (replaceValue === undefined) //delete repeated Object
return undefined;
else
keys = [];
}
if (keys.length > 0) //if keys exist, MOVE down a level
{ //...current or replaceValue is Object
depth++;
if (depth > 1)
dotName.push(key);
depthKeys[depth] = keys;
key = null; //disable move up
}
}
//if not already escaped, check for non-Object
else if (!key.includes(marker)) //...escapable types (including Date)
replaceValue = _checkEscape(this[key], options, rtnValue);
if (replaceValue !== null)
value = replaceValue;
if (depth > 0 && key !== null //if same depth and key exists
&& depthKeys[depth][0] == key) //...undefined Array items omitted
{
depthKeys[depth].shift()
while (depth > 0 && !depthKeys[depth].length)
{ //if no more keys, move up
depth--;
dotName.pop();
if (depth > 0)
depthKeys[depth].shift();
}
}
//===========
return value; //return from circular monitor replacer
//===========
}
//======================
return _circular_monitor; //return _circular_monitor closure function
//======================
}
//________________________________________________________________________________________________________
/**
* return escaped value if escapable and not ignored -- null if non-escapable or ignored (not circular)
* return undefined when circular ignored.(Object deleted)
*/
EZjsonPlus.prototype.escape = function EZjsonPlus_escape(value, options, rtnValue)
{
options = options || EZ.options.call(EZ.jsonPlus.options);
rtnValue = rtnValue || new EZ.rtnValue();
var dotName = options.dotName || '';
var marker = options.escapeMarker.wrap('@');
var valueType = EZ.getType(value, 'NaN Element')
if (valueType == 'Undefined')
valueType = 'undefined';
var escapeType = (options.repeatKey) ? 'circular' : valueType;
if (!options.escapeTypes.includes(escapeType))
return null;
var isIgnored = (options.ignore.includes(escapeType))
switch (escapeType)
{
case 'circular': return _escapeRepeated(options.repeatKey);
case 'Array': return _escapeArray();
case 'Element': return _escapeElement();
case 'Function': return _escapeFunction();
case 'RegExp': return _escapeRegExp();
case 'Date':
{
var dateStr = (isNaN(value)) ? value.toString()
: EZ.format.dateTime(value, 'ms').replace(/-/g, '/');
return (isIgnored) ? _escapeChanged(dateStr)
: _escapeValue("new Date('" + dateStr + "')", dateStr);
}
default: //NaN, Infinity, undefined, ...
{
return (isIgnored) ? _escapeChanged(valueType)
: _escapeValue(valueType, valueType);
}
}
//______________________________________________________________________________________________
/**
*
*/
function _escapeValue(newValue, displayValue)
{
var msg;
/*
//if (newValue instanceof Object) //Array, Element or Function
{
if (rtnData.safe !== true) //only allowed on clone of input Object
{
rtnData.safe = false;
return null;
}
}
*/
// . . . . . . . . . . . . . . . . .
switch (valueType)
{
case 'Element': //Element converted to Object
{
msg = dotName.wrap('[]') + ': ' + value.toString();
rtnValue.addListItem('html_elements', msg)
newValue[marker] = dotName + '=' + options.escapeHTML;
break;
}
case 'Function': //Function converted to Object
{
break;
}
case 'Date':
{
break;
}
case 'RegExp':
{ //TODO: consider if top level and options.script-true
//newValue = 'eval("$JSON$marker$=/m/;$JSON$marker$.lastIndex=5");$JSON$marker$)';
break;
}
/*
case 'undefined':
{
newValue = 'undefined';
break;
}
*/
default:
{
if (typeof(value) == 'object')
break;
newValue = valueType; //undefined, NaN, Infinity ...
}
}
// . . . . . . . . . . . . . . . . .
if (typeof(newValue) != 'object') //if escaped value not Object, convert to same
{ //...type as current value type
var dotNameValue = dotName + '=' + newValue;
if (!dotName || dotName == '$') //return String for top level value
newValue = marker + ': '+ newValue;
else if (valueType == 'Array') //return single item Array if valueType is Array
newValue = [marker + ':' + dotNameValue];
else
{ //otherwise return as single property Object
var obj = {};
obj[marker] = dotNameValue;
newValue = obj;
}
}
msg = (dotName && dotName != '$') ? dotName + '=' : '';
rtnValue.addListItem('escaped_values', msg + displayValue);
return newValue;
}
//______________________________________________________________________________________________
/**
*
*/
function _escapeCheckConstructor(val, dot)
{
val = val || value;
dot = dot || dotName;
if (!/(Array|Object)/.test(val.constructor.name))
{
var msg = dot.wrap('[]') + ': ' + val.constructor.name;
rtnValue.addListItem('ignored_constructors', msg);
}
}
//______________________________________________________________________________________________
/**
*
*/
function _escapeChanged(fromValue)
{
//var msg = options.dotName.wrap('[]') + ' "' + fromValue + '"\n'
// + ' --> "' + toValue + '"';
var msg; //...check if constructor ignored
_escapeCheckConstructor();
var toValue = JSON.stringify(value)
if (toValue === undefined)
toValue = '"undefined"';
msg = value;
if (valueType == 'Date')
msg = isNaN(value) ? value : EZ.format.dateTime(value, 'ms');
else if (valueType == 'Function')
msg = 'Function'
fromValue = fromValue + '';
msg = (dotName ? dotName.wrap('[]') : '')
+ ' ' + fromValue.wrap('[]')
+ (fromValue.concat(toValue).length > 30 ? '\n' : '')
+ ' --> ' + toValue.wrap('[]');
rtnValue.addListItem('changed_values', msg);
return null;
}
//______________________________________________________________________________________________
/**
*
*/
function _escapeDeleted(newValue, msg)
{
msg = (options.dotName || '...').wrap('[]') + ': ' + msg;
rtnValue.addListItem('deleted_values', msg);
return (escapeType == 'circular') ? undefined : null;
//return newValue; //(escapeType == 'circular') ? undefined : null;
}
//______________________________________________________________________________________________
/**
*
*/
function _escapeDeletedFunctions(newValue, msg)
{
msg = (options.dotName || '...').wrap('[]') + ': ' + msg;
rtnValue.addListItem('deleted_functions', msg);
return newValue;
}
//______________________________________________________________________________________________
/**
*
*/
function _escapeElement()
{
var formatted = EZ.format.Element(value, options.format.html);
var note = value.toString('brief');
if (!isIgnored)
return _escapeValue(formatted, note);
return _escapeDeleted(undefined, note);
}
//______________________________________________________________________________________________
/**
* String cannot look like pattern or JSON.stringify() discards
*/
function _escapeRegExp()
{ //alway add semi-colon to fool JSON.stringify()
var lastIndex = (value.lastIndex === 0) ? ';'
: ';#.lastIndex=' + value.lastIndex;
value = value.toString() + lastIndex;
if (isIgnored)
return _escapeChanged(value);
var note = value;
//if (!dotName) //unused top level idea??
// value = 'eval("$JSON$marker$=/m/;$JSON$marker$.lastIndex=5");$JSON$marker$)';
return _escapeValue(value, note);
}
//______________________________________________________________________________________________
/**
*
*/
function _escapeArray()
{
var msg;
var obj = {}; //for named Array properties
obj[marker] = options.dotName;
Object.keys(value).forEach(function(key)
{
if (!isNaN(key)) return;
obj[key] = value[key];
});
if (Object.keys(obj).length === 1)
return null; //no named Array properties
if (isIgnored)
{
delete obj[marker];
msg = 'Array named properties:\n' + JSON.stringify(obj,0,4);
return _escapeDeleted(null, msg);
}
msg = 'Array named properties:\n' + JSON.stringify(obj,0,4);
rtnValue.addListItem('escaped_values', msg);
//return value.concat([obj]) //add obj containing named properties
var newArray = value.concat([obj]);
return newArray; //_escapeValue(newArray);
}
//______________________________________________________________________________________________
/**
* escape or delete repeated Object
* TODO: support for ignore: repeated diff fron circular
*/
function _escapeRepeated(repeatKey)
{
return (isIgnored) ? _escapeDeleted(undefined, dotName)
: _escapeValue(repeatKey, repeatKey);
}
//______________________________________________________________________________________________
/**
* create Object containing function owner properties for JSON.stringify()
* Even functions are included since each may have properties.
*
* TODO: don't always ignore script
*/
function _escapeFunction()
{
var name = (value.name || 'anonymous');
var note = 'function ' + name + '(...)'
var msg = dotName.wrap('[]') + ': ' + note;
rtnValue.addListItem('functions', msg); //add to functions list
if (isIgnored)
return _escapeDeletedFunctions(undefined, note);
var keys = Object.keys(value);
if (keys.length === 0
|| (keys.length === 1 && keys.displayName))
return _escapeDeletedFunctions(undefined, 'function ' + name + '(script only)');
var obj = {};
keys.forEach(function(key)
{
_escapeCheckConstructor(value[key], dotName + '.' + key)
obj[key] = value[key];
});
return _escapeValue(obj, note);
//________________________________________________________________________________________
/**
* Determine if Function excluded and type of Object created if not -- little bit complex
* code from EZ.cloneDev.object()...
function _createFunctionClone()
{
var clone = '';
var isNative = false;
msg = 'function ' + (obj.name || 'anonymous') + '()';
var script = Function.prototype.toString.call(obj);
var isNative = (/\{\s*\[native code\]\s*\}/.test(script));
do
{ //-------------------------\\
if (isNative) //----- native function -----\\
{ //-----------------------------\\
if (options.exclude.includes('native'))
{
info.mergeListItem('excluded', msg + ' [native]', dotName)
}
else clone = obj; //keep as-is when not excluded
break;
}
//--------------------------\\
var keys = Object.keys(obj); //----- defined function -----\\
var idx = keys.indexOf('displayName'); //------------------------------\\
if (idx != -1)
keys.splice(idx,1);
var isEnum = (keys.length); //enumerable properties?
if (options.exclude.includes('Function')
&& (options.ignore.includes('script') && !isEnum))
{
info.mergeListItem('excluded', msg, dotName)
break;
}
if (options.ignore.includes('script') && !isEnum)
{
info.mergeListItem('excluded', msg + ' [no properties]', dotName);
break;
}
else if (options.ignore.includes('script')) //if excluding script
{
script = 'function ' + obj.name + '()';
info.mergeListItem('excluded', msg + ' [script only]', dotName)
}
if (options.exclude.includes('Function') //if excluding Function and not script
&& (!options.ignore.includes('script') || !isEnum)) //...or no enumerable properties
{
info.mergeListItem('excluded', msg, dotName)
break;
}
if (options.ignore.includes('script')) //otherwise if ignoring script . . .
{
if (!isEnum) //exclude function if no properties
{
info.mergeListItem('excluded', msg + ' [no properties]', dotName);
break;
}
script = 'function ' + obj.name + '()'; //exclude fn script
info.mergeListItem('excluded', msg + ' [script only]', dotName)
}
if (options.ignore.includes('ignored_constructors'))
{
clone = {} //clone as Object
info.mergeListItem('ignored_constructors', 'Function', dotName)
}
else
{
try
{
eval('clone=' + script);
}
catch (e)
{
clone = {};
info.addMessage('unable to clone function: ' + msg + ' @ ' + dotName.join('.').wrap('[]'))
info.addDetails(EZ.getStackTrace());
info.mergeListItem('excluded', msg + '[script syntax]', dotName)
}
}
}
while (false)
return clone;
}
*/
}
}
//______________________________________________________________________________________________
/**
* Specified Object is updated by un-escaping any escape markers found in json created via
* JSON.stringify() of the supplied Object.
*
* Markers are un-escaped in the order they appear in the json to insure any repeated Objects
* are available when repeat escape markers are subesequently encountered.
*/
EZjsonPlus.prototype.unescape = function JSONplus_unescape(obj, options, rtnValue)
{
options = EZ.options.call(EZ.jsonPlus.options, options);
rtnValue = rtnValue || new EZ.rtnValue();
var msg, json, pattern;
var errorCount = 0;
var escapeType = 'escaped values';
var escapeString = '';
var evalScript = '';
var marker = options.escapeMarker.wrap('@');
try
{
json = JSON.stringify(obj, null, 4);
do
{
if (options.isTestFunction || EZ.getTime(options.version) >= EZ.getTime('11-25-2016'))
{
var regex = RegExp('^"' + marker + ': (.*?)(;#[.].*)?"$');
json = json.replace(regex, function(all, script, more)
{
escapeString = all; //top level marker -- non-Object
evalScript = 'obj=' + script;
if (more) //e.g. /xyz/gim;#.lastIndex=1
evalScript += more.replace(/#/g, 'obj');
eval(evalScript);
return '';
});
if (!json) break;
regex = RegExp('(' //non-Array escape patterns: e.g. circular
//...html Element, RegExp, Date, Function
+ '[\\[{]?\\s*?"' //...start of Array or Object: [ or {
+ marker
+ '.*?((\\$.*?)=.*?)"' //...(2) script, (3) dotName of Object
+ '\\s*?[\\]}]' //...must only be followed by ] or }
+ '|' //Array with named properties pattern
+ "^\\s*" //...optional outer Array Object key
+ "(\".*?\":)?" //...start of Array
+ "\\s*\\[" //...everything up to marker
+ "[\\s\\S]*?"
+ '"' + marker + '":' //...marker Object key
+ '\\s*"'
+ '(.*?)' //...arrayDotName
+ '",' //...must be followed by comma
+ '[\\s\\S]*?\\n\\s*[}]' //...remaining marker Object
+ ')', 'gm');
json = json.replace(regex, function(all, outer, script, dotName, unusedKey, arrayDotName)
{
escapeString = all;
evalScript = '';
try
{ //named Array properties marker
if (arrayDotName !== undefined)
return _unescapeArray(obj, arrayDotName) ? '' : all;
if (script.endsWith('\\')) //not marker if ends backslash -- ideally regex should exclude
return ''; //...it is marker text inside String variable
//html Element marker
if (script.endsWith(options.escapeHTML))
return _unescapeElement(obj, script) ? '' : all;
//all other escape markers -- some marker validation
var equalCount = script.count('=');
var poundCount = script.count('#');
if ( (equalCount-1) != poundCount )
return _unescapeError('invalid escape marker: ' + script.wrap('[]'));
_unescapeValue(obj, script, dotName);
return '';
}
catch (e)
{
_unescapeError(e.message);
}
return all;
});
}
else
{
json = JSON.stringify(obj, null, 4);
var regex = RegExp('[\\[{]?\\s*?\\"' + marker + '.*?((\\$.*?)=.*?)"[\\s\\S]*?[\\]}]?', 'g');
json = json.replace(regex, function(all, set, dotName)
{
if (set.endsWith('\\')) //not marker if ends backslash -- ideally regex should exclude
return all; //...it is marker text inside String variable
void(obj); //exposes obj for viewing in debugger
escapeString = all;
evalScript = '';
if (!set.endsWith(options.escapeHTML)) //if not html marker. . .
{
escapeType = '[replace value]'; //1st replace all ";#" with dotName e.g. $.1=/xyz/;#.lastIndex=3
set = set.replace(/;#/g, ';' + dotName); // --> $.1=/xyz/;$.1.lastIndex=3
//then change number's in dotName e.g. $.1 --> $[1]
set = set.replace(/\.(\d+)(?=([.=]|$))/g, '[$1]');
set = set.replace(/\$/g, 'obj'); //and finally change $ --> obj
evalScript = set; //and save for exception reporting
eval(set);
}
else
{ //drop html marker and parse dotName w/ replace
escapeType = '[html]';