-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathl7json.PRG
More file actions
2868 lines (2551 loc) · 119 KB
/
l7json.PRG
File metadata and controls
2868 lines (2551 loc) · 119 KB
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
* L7Json.PRG
*
* 02/05/2010 [RP]
* BUG: If an array of non-objects is succeeded (physically) in the JSON
* string by an array of objects (or empty []), VFP error 1942 is
* encountered: objects cannot be assigned to arrays.
* Error does not occur if the sequence or properties is reveresed.
*
* --------------------------------------------------------- *
function L7DeepCopyViaJson(toObj)
return L7JsonParse(L7JsonSerialize(m.toObj))
endfunc
* --------------------------------------------------------- *
FUNCTION L7JsonSerialize(toObj)
LOCAL loJsonProc, lcRet
loJsonProc = CREATEOBJECT("L7JsonProcessor")
lcRet = loJsonProc.Serialize(m.toObj,2)
RETURN m.lcRet
ENDFUNC
* --------------------------------------------------------- *
FUNCTION L7JsonParse(tcJson)
LOCAL loJsonProc, loRet
loJsonProc = CREATEOBJECT("L7JsonProcessor")
loRet = loJsonProc.Parse(m.tcJson)
RETURN m.loRet
ENDFUNC
* ----------------------------------------------------- *
function L7LoadJsonWithKeys(tcJson, tcKeyList, tlIsFilename)
local loJsonProc, loParsed, lcJson
lcJson = iif(m.tlIsFileName, filetostr(m.tcJson), m.tcJson)
loJsonProc = CREATEOBJECT("L7JsonProcessor")
loJsonProc.keyPropertyNames = iif(vartype(m.tcKeyList) = "C", m.tcKeyList, "")
loParsed = loJsonProc.Parse(m.lcJson)
return m.loParsed
endfunc
* --------------------------------------------------------- *
FUNCTION getJsonIndentChars(tvSpace, tnLevel)
* [RP] see liked-named method in JSON class. Extracted to UDF so other classes can call it and
* maintain compatible indentation.
local lcReturnIndentChars, lcTypeOfSpace
lcReturnIndentChars = ""
lcTypeOfSpace = VARTYPE(m.tvSpace, .F.)
IF INLIST(m.lcTypeOfSpace, "C", "N")
lcReturnIndentChars = IIF(m.lcTypeOfSpace = "C", m.tvSpace, SPACE(m.tvSpace))
m.lcReturnIndentChars = REPLICATE(m.lcReturnIndentChars, m.tnLevel)
IF LEN(m.lcReturnIndentChars) > 0 OR ;
(m.tnLevel = 0 AND ((m.lcTypeOfSpace = "C" AND LEN(m.tvSpace) > 0) OR (m.lcTypeOfSpace = "N" AND m.tvSpace > 0)))
*
m.lcReturnIndentChars = CHR(10) + m.lcReturnIndentChars
ENDIF
ENDIF
return m.lcReturnIndentChars
endfunc && getJSONindentchars
* --------------------------------------------------------- *
FUNCTION L7CursorToJsonArray(tcAlias, toRet)
LOCAL loRec
IF VARTYPE(toRet) <> "O"
toRet = CREATEOBJECT("JsonArray")
ENDIF
IF NOT EMPTY(m.tcAlias)
SELECT (m.tcAlias)
ENDIF
SCAN
SCATTER MEMO NAME loRec
toRet.Add(m.loRec)
ENDSCAN
** [[ reset alias?
RETURN toRet
ENDFUNC && L7CURSORToJsonArray
*** ========================================================= ***
DEFINE CLASS L7JsonProcessor as JSON
usejsonfll = .F. && remove FLL dependency
* --------------------------------------------------------- *
FUNCTION Serialize(tvValue, tvSpace)
LOCAL lcRet
lcRet = this.Stringify(m.tvValue,, m.tvSpace) && stringify is Craig's name...
RETURN m.lcRet
ENDFUNC
ENDDEFINE
*** ========================================================= ***
define class L7JsonString as Line
* Pre-serialized JSON string encapsulation. For performance and/or round-trip avoidance.
* either:
* 1) obj = createobject('L7JsonString')
* obj.setString('{"var": value...}')
* 2) obj = createobject('L7JsonString', '{"var": value...}')
__json__ = '{}'
* -------------------------------------------------------- *
function init(tvStringOrObj)
if not empty(m.tvStringOrObj)
this.setString(m.tvStringOrObj)
endif
return
endfunc
* -------------------------------------------------------- *
function setString(tvStringOrObj)
if empty(m.tvStringOrObj)
this.__json__ = '{}'
else
if vartype(m.tvStringOrObj) = 'C'
this.__json__ = m.tvStringOrObj
else && object passed--perhaps being serialized for repetitive use performance reasons?
this.__json__ = L7JsonSerialize(m.tvStringOrObj)
endif
endif
return
endfunc
* -------------------------------------------------------- *
function _jsonSerialize(tvReplacer, tvSpace, tnLevel)
return this.__json__
endfunc
enddefine
*** ========================================================= ***
define class L7JsonStringCollection as Collection
* Pre-serialized JSON string collection. (See L7JsonString.) For performance and/or round-trip avoidance.
* 1) obj = createobject('L7JsonStringCollection')
* obj.add( <serialized_json> ) .. call as many times as needed
* -------------------------------------------------------- *
function _jsonSerialize(tvReplacer, tvSpace, tnLevel)
local lcStr, lnK, lcIndent
lcIndent = getJSONindentChars(m.tvSpace, m.tnLevel)
lcStr = '['
for lnK = 1 to this.Count
lcStr = m.lcStr + m.lcIndent + this.Item(m.lnK) + iif(m.lnK < this.Count, ",", "")
next
return m.lcStr + m.lcIndent + ']'
endfunc
enddefine
*** ========================================================= ***
DEFINE CLASS JsonArray as Collection && why not L7 prefix here??
ENDDEFINE
* 06/16/2009
* NOTE:
* The remainder of this file is adapted from Craig Boyd's JSON.PRG. Some of the changes,
* to cope with arrays needed to be embedded into the code, vs. subclassed, etc.
* Further, the JsonArray class above is a dependency, simple as it is.
*
* Aside from minor mods below, Randy Pearson, Cycla Corporation and L7 Framework users
* take no credit for the work below, and would be happy to feed any/all of this
* back to Craig and Sweet Pototo Software for consideration.
* #INCLUDE "json.h"
#DEFINE TOKENTYPE_UNDEFINED 0
#DEFINE TOKENTYPE_OBJECT 1
#DEFINE TOKENTYPE_ARRAY 2
#DEFINE TOKENTYPE_KEY 3
#DEFINE TOKENTYPE_STRING 4
#DEFINE TOKENTYPE_LOGICAL 5
#DEFINE TOKENTYPE_NUMBER 6
#DEFINE TOKENTYPE_DATETIME 8
#DEFINE TOKENTYPE_DATE 9
#DEFINE TOKENTYPE_NULL 10
#DEFINE TOKENTYPE_CURSOR 11
* RP added:
#DEFINE TOKENTYPE_COLLECTION 12
#DEFINE L7_INCLUDE_JSON_DLL .F. && squash compiler errors
DEFINE CLASS json AS custom
*-- Specifies what should be used in VFP as Undefined. Chr(0) is the default.
undefined = ""
*-- Specifies the class to use when deserializing JSON objects. The Empty class is the default.
defaultclass = "Empty"
*-- Specifies the module to get the class from when deserializing JSON Objects.
defaultmodule = ""
*-- Determines the format to use when parsing dates: 1 = ISO 8601 (default), 2 = new Date(), 3 = MS JSON Date
parsedatetype = 1
usejsonfll = L7_INCLUDE_JSON_DLL
trimstrings = .T.
*-- JSON key to be used when identifying cursors.
keyforcursors = "VFPData"
*-- JSON key to be used when identifying collection items.
keyforitems = "items"
*-- Property names to be used as key for collections, comma delimited list, in preference order.
keypropertynames = ""
*-- If .T. then the class and classlibrary keys/properties will be taken into consideration when parsing an object. If .F. then the defaults are used.
parserespectclass = .F.
*-- Target year last time GetTimezoneOffset was called.
PROTECTED _tzyear
_tzyear = .NULL.
*-- Start datetime for daylight saving last time GetTimezoneOffset was called.
PROTECTED _tzdaylightstart
_tzdaylightstart = .NULL.
*-- Start datetime of standard last time GetTimezoneOffset was called.
PROTECTED _tzstandardstart
_tzstandardstart = .NULL.
*-- Setting for tlUTCDatetime parameter last time GetTimezoneOffset was called.
PROTECTED _tzutc
_tzutc = .F.
*-- Standard offset last time GetTimezoneInformation was called.
PROTECTED _tzoffset
_tzoffset = .NULL.
*-- Daylight saving offset last time GetTimezoneInformation was called.
PROTECTED _tzdloffset
_tzdloffset = .NULL.
Name = "json"
*-- If .T. then all datetimes will be serialized to UTC equivalents and deserialized as UTC. If .F. then all datetimes will be conversely treated as Local datetimes.
useutcdatetime = .F.
PROTECTED name
PROTECTED classlibrary
PROTECTED addobject
PROTECTED addproperty
PROTECTED baseclass
PROTECTED class
PROTECTED cloneobject
PROTECTED comment
PROTECTED controlcount
PROTECTED controls
PROTECTED destroy
PROTECTED error
PROTECTED height
PROTECTED helpcontextid
PROTECTED newobject
PROTECTED objects
PROTECTED parent
PROTECTED parentclass
PROTECTED picture
PROTECTED readexpression
PROTECTED readmethod
PROTECTED removeobject
PROTECTED resettodefault
PROTECTED saveasclass
PROTECTED showwhatsthis
PROTECTED tag
PROTECTED whatsthishelpid
PROTECTED width
PROTECTED writeexpression
PROTECTED writemethod
PROCEDURE stringify
LPARAMETERS tvValue, tvReplacer, tvSpace, tnLevel, tcKey
*********************************************************************
*!* PURPOSE
*********************************************************************
*!* Serialize VFP objects, values, arrays and cursors to JSON
*********************************************************************
*!* PARAMETERS
*********************************************************************
*!* tvValue: (required)
*!* Either an instance of a VFP object/value/array or an Alias that will be stringified.
*!* Arrays must be sent in byref... JSON.Stringify(@MyArray)... otherwise only the first
*!* element of the array will be stringified
*!* tvReplacer: (optional)
*!* The optional tvReplacer parameter is either a string specifying a Function/Object.Method,
*!* a byref Array or a string containing a comma-delimited list of keys.
*!* If cFunction/cMethod is sent in it will be used via Evaluate. It is sent the parent object
*!* and each of the member keys and value pairs. Evaluate(m.tcReviver(parent, membername, value)'s
*!* return value is then serialized instead of the original object.
*!* If the return value equals This.Undefined, then the object is not serialized.
*!* If Array/CSV is sent in then it contains a list of keys (member names) that should be serialized.
*!* All other keys (members) will be ignored.
*!* tvSpace: (optional)
*!* A string to be used with line-breaks to indent the JSON produced, or it can be numeric specifying
*!* the number of spaces to use for indention. It simply makes the JSON easier to read by beautifying it.
*!* tnLevel: (internal-use)
*!* Tracks the hierarchy levels used for proper indention of JSON when tvSpace is sent in.
*!* tcKey: (internal-use)
*!* Allows the keys (member names) to be sent in when stringifying key/value pairs.
*********************************************************************
*!* RETURN
*********************************************************************
*!* String - JSON representation of tvValue sent in
*********************************************************************
LOCAL lcTypeOfValue, lcReturnJSON, lvValue, lcIndent, lcKey
LOCAL lcPointSettingWas, lcSeparatorSettingWas
m.lcReturnJSON = THIS.Undefined && default considered to be undefined
IF VARTYPE(m.tnLevel, .F.) != "N"
m.tnLevel = 0
ENDIF
IF m.tnLevel > 58 && Avoid nesting too deep error
RETURN (m.lcReturnJSON)
ENDIF
IF VARTYPE(m.tcKey) = "C"
m.lcKey = ["] + m.tcKey + [": ]
ELSE
m.lcKey = ""
ENDIF
m.lcTypeOfValue = TYPE("m.tvValue", 1)
IF m.lcTypeOfValue != "A" && if it's not an array then let's get the Type
m.lcTypeOfValue = VARTYPE(m.tvValue, .F.)
IF m.lcTypeOfValue = "O"
*!* ToJSON() method shouldn't serialize, simply pass back a value or undefined
* rp: Classes that "know" how to serialize themself should provide a _jsonSerialize() method.
IF PEMSTATUS(m.tvValue, "tojson", 5) && if object has a ToJSON() method then use it to get value to serialize
m.lvValue = EVALUATE("m.tvValue.tojson()")
ELSE
m.lvValue = m.tvValue
ENDIF
ELSE
m.lvValue = m.tvValue
ENDIF
ENDIF
*!* save settings - handle localization
m.lcPointSettingWas = SET("Point")
m.lcSeparatorSettingWas = SET("Separator")
IF m.lcPointSettingWas != "."
SET POINT TO "."
ENDIF
IF m.lcSeparatorSettingWas != ","
SET SEPARATOR TO ","
ENDIF
DO CASE
CASE m.lcTypeOfValue = "A" && Array
m.lcReturnJSON = THIS.SerializeArray(@m.tvValue, @m.tvReplacer, tvSpace, tnLevel)
CASE m.lcTypeOfValue = "C" && Character, Memo, Varchar, Varchar (Binary)
*!* are we on the first pass (cursor serialization would never be nested in an array/object) and is it an alias?
IF m.tnLevel = 0 AND USED(m.lvValue)
m.lcReturnJSON = THIS.Serializecursor(m.lvValue, @m.tvReplacer, m.tvSpace, m.tnLevel)
ELSE && then it must be a string
IF THIS.TrimStrings
m.lcReturnJSON = THIS.SerializeString(ALLTRIM(m.lvValue))
ELSE
m.lcReturnJSON = THIS.SerializeString(m.lvValue)
ENDIF
ENDIF
CASE m.lcTypeOfValue = "D" && Date
m.lcReturnJSON = THIS.SerializeDate(m.lvValue)
CASE m.lcTypeOfValue = "G" && General
m.lcReturnJSON = THIS.Undefined
CASE m.lcTypeOfValue = "L" && Logical
m.lcReturnJSON = THIS.SerializeLogical(m.lvValue)
CASE INLIST(m.lcTypeOfValue, "N", "Y") && Numeric, Float, Double, Integer, or Currency
m.lcReturnJSON = THIS.SerializeNumber(m.lvValue)
CASE m.lcTypeOfValue = "O" && Object
IF PEMSTATUS(m.lvValue, "Class", 5) AND BasedOn(m.lvValue, "JsonArray") && adds L7Utils dependency, had been LOWER(lvValue.Class) == LOWER("JsonArray")
m.lcReturnJSON = THIS.SerializeJsonCollection(@m.lvValue, @m.tvReplacer, tvSpace, tnLevel)
ELSE
m.lcReturnJSON = THIS.SerializeObject(@m.lvValue, @m.tvReplacer, tvSpace, tnLevel)
ENDIF
CASE m.lcTypeOfValue = "Q" && Blob, Varbinary
m.lcReturnJSON = THIS.Undefined
CASE m.lcTypeOfValue = "T" && DateTime
m.lcReturnJSON = THIS.SerializeDatetime(m.lvValue)
CASE m.lcTypeOfValue = "U" && Unknown or variable does not exist
m.lcReturnJSON = THIS.Undefined
CASE m.lcTypeOfValue = "X" && Null
m.lcReturnJSON = THIS.SerializeNull()
OTHERWISE
m.lcReturnJSON = THIS.Undefined
ENDCASE
*!* revert settings if applicable - handle localization
IF m.lcPointSettingWas != "."
SET POINT TO (m.lcPointSettingWas)
ENDIF
IF m.lcSeparatorSettingWas != ","
SET SEPARATOR TO (m.lcSeparatorSettingWas)
ENDIF
IF !THIS.IsUndefined(m.lcReturnJSON)
m.lcIndent = THIS.GetIndentChars(m.tvSpace, m.tnLevel)
IF m.tnLevel != 0
m.lcReturnJSON = m.lcIndent + m.lcKey + m.lcReturnJSON
ENDIF
ENDIF
RETURN (m.lcReturnJSON)
*********************************************************************
*!* ADDITIONAL NOTES AND COMMENTS
*********************************************************************
*!* Online JSON Validator
*!* http://www.jsonlint.com/
*********************************************************************
ENDPROC
PROCEDURE parse
LPARAMETERS tcJSONString, tcReviver, tvValue, ;
tnTokenType, tnTokenStart, tnTokenLength, tcTokenText
*********************************************************************
*!* PURPOSE
*********************************************************************
*!* Parse JSON to create/fill a VFP object, value, array or cursor
*********************************************************************
*!* PARAMETERS
*********************************************************************
*!* tcJSONString: (required)
*!* A string of valid JSON that will be parsed to return an instance of a VFP object, value, array or cursor
*!* If you are expecting an array back, then you must send an Array in byref to the tvValue parameter.
*!* The array will be automatically dimensioned appropriately
*!* tcReviver: (optional)
*!* A string containing a "Function" or "Object.Method" that will be
*!* evaluated via VFP's Evaluate() function.
*!* It is sent the parent object and each of the member keys and value pairs, such as...
*!* Evaluate(m.tcReviver(parent, membername, value). Its return value is then used in lieu of the member.
*!* If its return value equals This.Undefined, then the member is ignored, thus allowing you to filter what is parsed.
*!* tvValue: (optional)
*!* An instance of a VFP object\value\array or an Alias for the cursor to be filled or created.
*!* If you are parsing a cursor, but do not send in an alias then a unique alias name will
*!* be generated for you and used as the return value of the parse function.
*!* As noted above, if you are dealing with an array, then you must send it in byref.
*!* tnTokenType: (internal-use)
*!* Used internally to track the type of token being returned from This.GetNextToken().
*!* Interested parties can see the list of valid token types in json.h (I wish VFP had enums)
*!* tnTokenStart: (internal-use)
*!* Used internally to track the start position of the TokenText within the JSON
*!* of the token being returned by This.GetNextToken()
*!* tnTokenLength: (internal-use)
*!* Used internally to track the length of the TokenText of the token being returned by This.GetNextToken()
*!* tcTokenText: (internal-use)
*!* Used internally to track the TokenText generated by This.GetNextToken() when This.Parse is called recursively.
*********************************************************************
*!* RETURN
*********************************************************************
*!* Any - Depends on parameters and settings
*********************************************************************
LOCAL lvReturnVariableOrAlias, lnStringLength, lnStartPosition
m.tnTokenType = TOKENTYPE_UNDEFINED
m.tnTokenStart = 0
m.tnTokenLength = 0
m.tcTokenText = THIS.Undefined
m.lvReturnVariableOrAlias = THIS.Undefined
IF VARTYPE(m.tcJSONString, .F.) = "C"
IF !EMPTY(m.tcJSONString)
m.lnStringLength = LEN(m.tcJSONString)
m.lnStartPosition = 1
m.tcTokenText = THIS.GetNextToken(@m.tcJSONString, m.lnStringLength, m.lnStartPosition, ;
@m.tnTokenType, @m.tnTokenStart, @m.tnTokenLength)
DO CASE
CASE m.tnTokenType = TOKENTYPE_OBJECT
m.lvReturnVariableOrAlias = THIS.DeserializeObject(m.tcTokenText, @m.tcReviver) && [RP], @m.tvValue)
* [RP] added case:
CASE m.tnTokenType = TOKENTYPE_COLLECTION
m.lvReturnVariableOrAlias = THIS.DeserializeJsonCollection(m.tcTokenText, @m.tcReviver)
CASE m.tnTokenType = TOKENTYPE_ARRAY
m.lvReturnVariableOrAlias = THIS.DeserializeArray(m.tcTokenText, @m.tcReviver, @m.tvValue)
CASE m.tnTokenType = TOKENTYPE_KEY
m.lvReturnVariableOrAlias = THIS.DeserializeKey(m.tcTokenText)
CASE m.tnTokenType = TOKENTYPE_DATETIME
m.lvReturnVariableOrAlias = THIS.DeserializeDatetime(m.tcTokenText)
CASE m.tnTokenType = TOKENTYPE_STRING
m.lvReturnVariableOrAlias = THIS.DeserializeString(m.tcTokenText)
CASE m.tnTokenType = TOKENTYPE_LOGICAL
m.lvReturnVariableOrAlias = THIS.DeserializeLogical(m.tcTokenText)
CASE m.tnTokenType = TOKENTYPE_NUMBER
m.lvReturnVariableOrAlias = THIS.DeserializeNumber(m.tcTokenText)
CASE m.tnTokenType = TOKENTYPE_DATE
m.lvReturnVariableOrAlias = THIS.DeserializeDate(m.tcTokenText)
CASE m.tnTokenType = TOKENTYPE_NULL
m.lvReturnVariableOrAlias = THIS.DeserializeNull(m.tcTokenText)
CASE m.tnTokenType = TOKENTYPE_CURSOR
m.lnStartPosition = m.lnStartPosition + (AT("[", SUBSTR(m.tcJSONString, m.lnStartPosition),1) - 1)
m.tcTokenText = THIS.GetNextToken(@m.tcJSONString, m.lnStringLength, m.lnStartPosition, ;
@m.tnTokenType, @m.tnTokenStart, @m.tnTokenLength)
m.lvReturnVariableOrAlias = THIS.DeserializeCursor(m.tcTokenText, @m.tcReviver, m.tvValue)
OTHERWISE && TOKENTYPE_UNDEFINED
m.lvReturnVariableOrAlias = THIS.Undefined
ENDCASE
IF m.tnTokenType != TOKENTYPE_ARRAY && arrays have to be byref
m.tvValue = m.lvReturnVariableOrAlias
ENDIF
ENDIF
ENDIF
RETURN (m.lvReturnVariableOrAlias)
ENDPROC
PROTECTED PROCEDURE quote
LPARAMETERS tcString
*********************************************************************
*!* PURPOSE
*********************************************************************
*!* Take a VFP string, escape it and surround it with quotes
*********************************************************************
*!* PARAMETERS
*********************************************************************
*!* tcString
*!* A VFP string that needs to be escaped and wrapped as part of serializing it to JSON string
*********************************************************************
*!* RETURN
*********************************************************************
*!* String - escaped and quoted equivalent of the string sent in
*********************************************************************
LOCAL lcReturnWrappedInQuotes
m.lcReturnWrappedInQuotes = THIS.EscapeChars(m.tcString)
m.lcReturnWrappedInQuotes = ["] + m.lcReturnWrappedInQuotes + ["]
RETURN (m.lcReturnWrappedInQuotes)
ENDPROC
PROCEDURE isundefined
LPARAMETERS tvValueToCheck
*********************************************************************
*!* PURPOSE
*********************************************************************
*!* Check whether a value matches the setting for This.Undefined
*********************************************************************
*!* PARAMETERS
*********************************************************************
*!* tvValueToCheck
*!* The value to check when determining whether it is Undefined
*********************************************************************
*!* RETURN
*********************************************************************
*!* Logical - indicating whether the value sent in is considered Undefined
*********************************************************************
LOCAL llReturnUndefined
m.llReturnUndefined = VARTYPE(m.tvValueToCheck, .F.) = "C"
m.llReturnUndefined = m.llReturnUndefined AND (m.tvValueToCheck == THIS.Undefined)
RETURN (m.llReturnUndefined)
ENDPROC
PROTECTED PROCEDURE escapechars
LPARAMETERS tcStringToEscape
*********************************************************************
*!* PURPOSE
*********************************************************************
*!* Escape chars according to RFC4627 section 2.5
*********************************************************************
*!* PARAMETERS
*********************************************************************
*!* tcStringToEscape
*!* The string to be escaped a valid JSON string
*********************************************************************
*!* RETURN
*********************************************************************
*!* String - escaped equivalent of the string sent in
*********************************************************************
LOCAL lcReturnEscapedString, lnCharCounter, lnAsc, lcCurrentChar
m.lcReturnEscapedString = ""
#IF L7_INCLUDE_JSON_DLL
IF This.UseJSONFLL && using FLL to escape chars (best performance)
IF ATC("JSON.FLL", SET("Library")) = 0
SET LIBRARY TO JSON.FLL
ENDIF
m.lcReturnEscapedString = JSONEscapeStr(m.tcStringToEscape)
*********************************************************************
*!* NOTE:
*********************************************************************
*!* If you want to escape all chars with ASCII values < 32 and > 126
*!* you can use the following line of code instead of the above:
*!*
*!* m.lcReturnEscapedString = JSONEncodeStr(m.tcStringToEscape)
*!*
*********************************************************************
ELSE && Use VFP to escape chars (no dependency on FLL)
#ENDIF
FOR m.lnCharCounter = 1 TO LEN(m.tcStringToEscape)
m.lcCurrentChar = SUBSTR(m.tcStringToEscape, m.lnCharCounter, 1)
m.lnAsc = ASC(m.lcCurrentChar)
IF (m.lnAsc < 32 ;
OR m.lnAsc > 255 ;
OR INLIST(m.lnAsc, 34, 92, 127, 129, 141, 143, 144, 157, 173)) && needs to be escaped
IF m.lnAsc > 92 OR !INLIST(m.lnAsc, 8, 9, 10, 12, 13, 34, 92)
m.lcCurrentChar = "\u" + RIGHT(TRANSFORM(m.lnAsc, "@0"), 4)
ELSE
DO CASE
CASE m.lnAsc = 8
m.lcCurrentChar = "\b"
CASE m.lnAsc = 9
m.lcCurrentChar = "\t"
CASE m.lnAsc = 10
m.lcCurrentChar = "\n"
CASE m.lnAsc = 12
m.lcCurrentChar = "\f"
CASE m.lnAsc = 13
m.lcCurrentChar = "\r"
CASE m.lnAsc = 34
m.lcCurrentChar = [\"]
CASE m.lnAsc = 92
m.lcCurrentChar = "\\"
ENDCASE
ENDIF
ENDIF
m.lcReturnEscapedString = m.lcReturnEscapedString + m.lcCurrentChar
ENDFOR
#IF L7_INCLUDE_JSON_DLL
ENDIF
#ENDIF
RETURN (m.lcReturnEscapedString)
*********************************************************************
*!* ADDITIONAL NOTES AND COMMENTS
*********************************************************************
*!* Below are the results of a test I ran via JSON.stringify from json2.js.
*!* It shows which ASCII chars are escaped and the format used.
*!* ASC#: Return
*!* The format is based on RFC4627 and...
*!* addition information regarding RFC4627 can be found...
*!* http://www.ietf.org/rfc/rfc4627.txt?number=4627
*********************************************************************
*!* 0: "\u0001"
*!* 1: "\u0001"
*!* 2: "\u0002"
*!* 3: "\u0003"
*!* 4: "\u0004"
*!* 5: "\u0005"
*!* 6: "\u0006"
*!* 7: "\u0007"
*!* 8: "\b"
*!* 9: "\t"
*!* 10: "\n"
*!* 11: "\u000b"
*!* 12: "\f"
*!* 13: "\r"
*!* 14: "\u000e"
*!* 15: "\u000f"
*!* 16: "\u0010"
*!* 17: "\u0011"
*!* 18: "\u0012"
*!* 19: "\u0013"
*!* 20: "\u0014"
*!* 21: "\u0015"
*!* 22: "\u0016"
*!* 23: "\u0017"
*!* 24: "\u0018"
*!* 25: "\u0019"
*!* 26: "\u001a"
*!* 27: "\u001b"
*!* 28: "\u001c"
*!* 29: "\u001d"
*!* 30: "\u001e"
*!* 31: "\u001f"
*!* 32: " "
*!* 33: "!"
*!* 34: "\""
*!* 35: "#"
*!* 36: "$"
*!* 37: "%"
*!* 38: "&"
*!* 39: "&"
*!* 40: "("
*!* 41: ")"
*!* 42: "*"
*!* 43: "+"
*!* 44: ","
*!* 45: "-"
*!* 46: "."
*!* 47: "/"
*!* 48: "0"
*!* 49: "1"
*!* 50: "2"
*!* 51: "3"
*!* 52: "4"
*!* 53: "5"
*!* 54: "6"
*!* 55: "7"
*!* 56: "8"
*!* 57: "9"
*!* 58: ":"
*!* 59: ";"
*!* 60: "<"
*!* 61: "="
*!* 62: ">"
*!* 63: "?"
*!* 64: "@"
*!* 65: "A"
*!* 66: "B"
*!* 67: "C"
*!* 68: "D"
*!* 69: "E"
*!* 70: "F"
*!* 71: "G"
*!* 72: "H"
*!* 73: "I"
*!* 74: "J"
*!* 75: "K"
*!* 76: "L"
*!* 77: "M"
*!* 78: "N"
*!* 79: "O"
*!* 80: "P"
*!* 81: "Q"
*!* 82: "R"
*!* 83: "S"
*!* 84: "T"
*!* 85: "U"
*!* 86: "V"
*!* 87: "W"
*!* 88: "X"
*!* 89: "Y"
*!* 90: "Z"
*!* 91: "["
*!* 92: "\\"
*!* 93: "]"
*!* 94: "^"
*!* 95: "_"
*!* 96: "`"
*!* 97: "a"
*!* 98: "b"
*!* 99: "c"
*!* 100: "d"
*!* 101: "e"
*!* 102: "f"
*!* 103: "g"
*!* 104: "h"
*!* 105: "i"
*!* 106: "j"
*!* 107: "k"
*!* 108: "l"
*!* 109: "m"
*!* 110: "n"
*!* 111: "o"
*!* 112: "p"
*!* 113: "q"
*!* 114: "r"
*!* 115: "s"
*!* 116: "t"
*!* 117: "u"
*!* 118: "v"
*!* 119: "w"
*!* 120: "x"
*!* 121: "y"
*!* 122: "z"
*!* 123: "{"
*!* 124: "|"
*!* 125: "}"
*!* 126: "~"
*!* 127: "\u007f"
*!* 128: ""
*!* 129: "\u0081"
*!* 130: ""
*!* 131: ""
*!* 132: ""
*!* 133: "
"
*!* 134: ""
*!* 135: ""
*!* 136: ""
*!* 137: ""
*!* 138: ""
*!* 139: ""
*!* 140: ""
*!* 141: "\u008d"
*!* 142: ""
*!* 143: "\u008f"
*!* 144: "\u0090"
*!* 145: ""
*!* 146: ""
*!* 147: ""
*!* 148: ""
*!* 149: ""
*!* 150: ""
*!* 151: ""
*!* 152: ""
*!* 153: ""
*!* 154: ""
*!* 155: ""
*!* 156: ""
*!* 157: "\u009d"
*!* 158: ""
*!* 159: ""
*!* 160: " "
*!* 161: "¡"
*!* 162: "¢"
*!* 163: "£"
*!* 164: "¤"
*!* 165: "¥"
*!* 166: "¦"
*!* 167: "§"
*!* 168: "¨"
*!* 169: "©"
*!* 170: "ª"
*!* 171: "«"
*!* 172: "¬"
*!* 173: "\u00ad"
*!* 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: "ÿ"
*********************************************************************
ENDPROC
PROCEDURE unescapechars
LPARAMETERS tcJSONStringToUnescape
*********************************************************************
*!* PURPOSE
*********************************************************************
*!* Unescape a JSON string according to RFC4627 section 2.5
*********************************************************************
*!* PARAMETERS
*********************************************************************
*!* tcJSONStringToUnescape
*!* A JSON string that is to be unescaped
*********************************************************************
*!* RETURN
*********************************************************************
*!* String - escaped equivalent of the JSON string sent in
*********************************************************************
LOCAL lcReturnUnescapedString, lnCharCounter, lnStringLength
LOCAL lnEscapePosition, lnEscapeOccurrence, lnPositionAfterPreviousEscape
LOCAL lnPositionDifference, lcCurrentChar
m.lcReturnUnescapedString = ""
#IF L7_INCLUDE_JSON_DLL
IF This.UseJSONFLL && using FLL to unescape chars (best performance)
IF ATC("JSON.FLL", SET("Library")) = 0
SET LIBRARY TO JSON.FLL
ENDIF
m.lcReturnUnescapedString = JSONUnescapeStr(m.tcJSONStringToUnescape)
ELSE && Use VFP to unescape chars (no dependency on FLL)
#ENDIF
m.lnEscapePosition = AT("\", m.tcJSONStringToUnescape)
IF m.lnEscapePosition > 0 && do any escaped chars exist?
m.lcReturnUnescapedString = LEFT(m.tcJSONStringToUnescape, m.lnEscapePosition - 1) && add everything before the escape to the return string
m.lnEscapeOccurrence = 1
DO WHILE m.lnEscapePosition > 0 && walk all the escape characters in the string
m.lcCurrentChar = SUBSTR(m.tcJSONStringToUnescape, m.lnEscapePosition + 1, 1)
m.lnPositionAfterPreviousEscape = m.lnEscapePosition + 2
DO CASE
CASE m.lcCurrentChar = "b" && ASCII 8
m.lcCurrentChar = CHR(8)
CASE m.lcCurrentChar = "t" && ASCII 9
m.lcCurrentChar = CHR(9)
CASE m.lcCurrentChar = "n" && ASCII 10
m.lcCurrentChar = CHR(10)
CASE m.lcCurrentChar = "f" && ASCII 12
m.lcCurrentChar = CHR(12)
CASE m.lcCurrentChar = "r" && ASCII 13
m.lcCurrentChar = CHR(13)
CASE m.lcCurrentChar = ["] && ASCII 34
m.lcCurrentChar = CHR(34)
CASE m.lcCurrentChar = "\" && ASCII 92
m.lnEscapeOccurrence = m.lnEscapeOccurrence + 1
CASE m.lcCurrentChar = "u" && u00XX
m.lcCurrentChar = CHR(EVALUATE("0x" + SUBSTR(m.tcJSONStringToUnescape, m.lnEscapePosition + 2, 4)))
m.lnPositionAfterPreviousEscape = m.lnPositionAfterPreviousEscape + 4
ENDCASE
m.lcReturnUnescapedString = m.lcReturnUnescapedString + m.lcCurrentChar
m.lnEscapeOccurrence = m.lnEscapeOccurrence + 1
m.lnEscapePosition = AT("\", m.tcJSONStringToUnescape, m.lnEscapeOccurrence)
IF m.lnEscapePosition > 0
m.lnPositionDifference = ((m.lnEscapePosition - m.lnPositionAfterPreviousEscape))
m.lcReturnUnescapedString = m.lcReturnUnescapedString + SUBSTR(m.tcJSONStringToUnescape, m.lnPositionAfterPreviousEscape, m.lnPositionDifference)
ELSE
m.lcReturnUnescapedString = m.lcReturnUnescapedString + SUBSTR(m.tcJSONStringToUnescape, m.lnPositionAfterPreviousEscape)
ENDIF
ENDDO
ELSE
m.lcReturnUnescapedString = m.tcJSONStringToUnescape
ENDIF
#IF L7_INCLUDE_JSON_DLL
ENDIF
#ENDIF
RETURN (m.lcReturnUnescapedString)
*********************************************************************
*!* ADDITIONAL NOTES AND COMMENTS
*********************************************************************
*!* See This.Escape() for additional information regarding JSON char escaping
*********************************************************************
ENDPROC
PROTECTED PROCEDURE SerializeJsonCollection
LPARAMETERS toColl, tvReplacer, tvSpace, tnLevel
LOCAL lnCounter
LOCAL lcColumn, lcAllColumns, lcRow, lcArrayIndent, lcMultiIndent
LOCAL lcReturnJSONArray
local lvItem, lcItemJson
m.lcArrayIndent = THIS.GetIndentChars(m.tvSpace, m.tnLevel)
m.lcReturnJSONArray = ""
FOR m.lnCounter = 1 TO m.toColl.Count
lvItem = toColl.Item(m.lnCounter)
lcItemJson = THIS.stringify(m.lvItem, @m.tvReplacer, m.tvSpace, m.tnLevel + 1)
IF THIS.Isundefined(m.lcItemJson)
LOOP && is this appropriate??
ENDIF
m.lcReturnJSONArray = m.lcReturnJSONArray + IIF(!EMPTY(m.lcReturnJSONArray), ",", "") + m.lcItemJson
ENDFOR
m.lcReturnJSONArray = "[" + m.lcReturnJSONArray + m.lcArrayIndent + "]"
RETURN (m.lcReturnJSONArray)
ENDPROC
PROTECTED PROCEDURE serializearray
LPARAMETERS taArray, tvReplacer, tvSpace, tnLevel
*********************************************************************
*!* PURPOSE
*********************************************************************
*!* Serialize a VFP array to JSON