forked from vespina/json
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjson.PRG
More file actions
3541 lines (3025 loc) · 101 KB
/
Copy pathjson.PRG
File metadata and controls
3541 lines (3025 loc) · 101 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
* JSON.PRG
* 100% VFP Json Parser
*
* Version: 1.20
* Author: V. Espina / A. Ferreira
*
*
* BASIC USAGE
*
* DO json
* string = json.Stringify(object)
* string = json.Stringify(@array)
* object = json.Parse(string)
* string = json.Beautify(string | object)
*
*
* JSON CONSTRUCTION
*
* LOCAL cFName, cLName
* cFName = "Victor"
* cLName = "Espina"
* TEXT TO cJSON NOSHOW
* {
* firstName: cFName,
* lastName: cLName,
* fullName: (this.firstName + SPACE(1) + this.lastName),
* age: 44,
* nacionality: "VENEZUELAN",
* dob: "1970-11-18",
* hobbies: ["Programming", "Music", "SciFi"],
* languages: [
* { id: "ES", caption: "Spanish", level: "Mother" },
* { id: "EN", caption: "English", level: "Good" }
* ]
* }
* ENDTEXT
*
* oVES = json.Parse(cJSON)
* ?oVES.firstName ---> "Victor"
* ?oVES.fullName ---> "Victor Espina"
* ?oVES.hobbies.Count --> 2
* ?oVES.hobbies.Item[1] --> "Programming"
* ?oVES.Languages.Item[1].id --> "ES"
*
*
*
* ERROR HANDLING
* The library uses a singleton class to handle errors in
* all classes, so any error ocurred anywhere in the library
* can be checked using json.lastError object:
*
* IF json.lastError.hasError && Something went wrong
* ?"Error #", json.lastError.errorNo
* ?"Message", json.lastError.Message
* ?"Procedure", json.lastError.Procedure
* ?"Line #", json.lastError.lineNo
* ?"Details", json.lastError.Details
* ENDIF
*
*
*
* CURSOR HANDLING
* JSON library can convert a data cursor into a JSON string representation, optionally
* including the cursor schema. If a cursor is converted to JSON string including the schema
* the cursor can be recreated later exactly as it was (using parseCursor). If no schema was
* added, then cursor can still be recreated, but the library will deduce the schema from
* the cursor data (using toCursor).
*
* string = json.Stringify("alias" [,withSchema] [,datasession]) [8]
* json.parseCursor(string [, "alias"] [,datasession]) [1]
* json.toCursor(string | object, "alias" [,datasession]) [2]
*
*
* SCHEMAS
* Schemas allows to declare public reusable cursor structures (schemas) and
* create empty cursors based on those pre-declared schemas. Schemas are
* based on jsonSchema class, wich can be used directly also for on-the-fly
* dinamically cursor creation.
*
* oSchema = json.Schemas.New(name) [3]
* oSchema = json.Schemas.newFromCursor(name, "alias" [,datasession])
* oSchema = json.Schemas.newFromString(name, string) [4]
* bool = json.Schemas.Create(cursorName, schemaName [,datasession])
* oSchema = json.Schemas.Get(name)
* bool = json.Schemas.Exist(name)
* bool = json.Schemas.Delete(name)
*
* bool = oSchema.initWithAlias("alias" [,datasession])
* bool = oSchema.initWithJSON(string) [1]
* bool = oSchema.addColumn(name, type [,lon] [,dec])
* bool = oSchema.addColumn(object) [5]
* bool = oSchema.addColumnFromString(string) [6]
* bool = oSchema.existColumn(name)
* bool = oSchema.delColumn(name)
* string = oSchema.toString([bool]) [7]
* bool = oSchema.toCursor("alias" [,datasession])
*
*
*
* NOTES
* [1] The JSON string must be generated using Stringify method and INCLUDE the cursor schema. To convert
* other JSON strings to cursor, use toCursor().
*
* [2] The JSON string must be an array of objects, ex:
* cJSON = '[{fname: "Victor", lname: "Espina", age: 44}, {fname: "Angel", lname: "Ferreira", age: 40}]'
* json.toCursor(cJSON, "qteam")
* SELECT qteam
* SCAN
* ?fname, lname, age
* ENDSCAN
*
* [3] All schemas has to be identified with an unique name. This name would be used later to access a
* particular schema, ex:
*
* json.Schemas.newFromString("userInfo","login C (25), fullname C (50), pwd C (50), role C (50)")
* ...
* json.Schemas.create("quser", "userInfo")
* insert into quser values ('vespina','Victor Espina','1234','Admin')
*
* [4] Example:
* oSchema = json.Schemas.newFromString("fname C(50), lname C(50), age N (3), dob D")
*
* [5] Object must be an instance of jsonColumn class
* [6] Example:
* oSchema.addColumnFromString("lname C (50)")
*
* [7] The optional bool parameters allows to indicate that a JSON string representation of the schema is required
* [8] If optional bool parameter withSchema is passed as True, the resulting JSON string will include the cursor's schema. Use
* this if you plan to recreate the cursor later from the JSON string.
*
*
#DEFINE VFP_JSON_LANG "EN" && Cambiar a ES para mensajes en espanol
#DEFINE VFP_NOENCODABLE_PROPS "-controls-controlcount-objects-parent-class-baseclass-classlibrary-parentclass-helpcontextid-whatsthishelpid-top-left-width-height-picture-_customproplist-activecontrol-activeform-forms-"
#DEFINE CRLF CHR(13)+CHR(10)
#IF VFP_JSON_LANG=="EN"
#DEFINE VFP_JSON_MSG_001 "The schema name is missing."
#DEFINE VFP_JSON_MSG_002 "The specified schema does not exist."
#DEFINE VFP_JSON_MSG_003 "The specified scheme already exists."
#DEFINE VFP_JSON_MSG_004 "The name of the column is not specified."
#DEFINE VFP_JSON_MSG_005 "The type of the column is not specified."
#DEFINE VFP_JSON_MSG_006 "The long of the column is not specified."
#DEFINE VFP_JSON_MSG_007 "The specified column name already exists."
#DEFINE VFP_JSON_MSG_008 "Invalid column type."
#DEFINE VFP_JSON_MSG_009 "Column structure is not specified."
#DEFINE VFP_JSON_MSG_010 "The cursor name is not specified."
#DEFINE VFP_JSON_MSG_011 "The cursor name is not in use."
#DEFINE VFP_JSON_MSG_012 "The string scheme is not specified."
#DEFINE VFP_JSON_MSG_013 "The provided JSON string is not well formatted (invalid attribute name)"
#DEFINE VFP_JSON_MSG_014 "Unbalanced JSON string"
#DEFINE VFP_JSON_MSG_015 "The provided JSON string is not well formatted (invalid variable name)"
#DEFINE VFP_JSON_MSG_016 "The provided JSON string does not represents a valid cursor object"
#DEFINE VFP_JSON_MSG_017 "Missing parameter"
#DEFINE VFP_JSON_MSG_018 "Invalid parameter"
#DEFINE VFP_JSON_MSG_019 "The provided JSON string is not well formatted"
#DEFINE VFP_JSON_MSG_020 "The schema is empty"
#DEFINE VFP_JSON_MSG_021 "The provided JSON is not an array of objects"
#DEFINE VFP_JSON_MSG_022 "Alias already exists"
#DEFINE VFP_JSON_BEAUTIFY_MARGIN 2
#ENDIF
#IF VFP_JSON_LANG == "ES"
#DEFINE VFP_JSON_MSG_001 "Falta el nombre del esquema"
#DEFINE VFP_JSON_MSG_002 "El esquema especificado no existe."
#DEFINE VFP_JSON_MSG_003 "El esquema especificado ya existe."
#DEFINE VFP_JSON_MSG_004 "No se especifica el nombre de la columna."
#DEFINE VFP_JSON_MSG_005 "No se especifica el tipo de columna."
#DEFINE VFP_JSON_MSG_006 "No se especifica la longitud de la columna."
#DEFINE VFP_JSON_MSG_007 "El nombre de columna especificado ya existe."
#DEFINE VFP_JSON_MSG_008 "Tipo de columna no válida."
#DEFINE VFP_JSON_MSG_009 "No se especifica la estructura de columnas."
#DEFINE VFP_JSON_MSG_010 "El nombre del cursor no se especifica."
#DEFINE VFP_JSON_MSG_011 "El nombre del cursor no está en uso."
#DEFINE VFP_JSON_MSG_012 "El esquema de cadenas no está especificado."
#DEFINE VFP_JSON_MSG_013 "La cadena JSON proporcionada no está bien formateada (nombre de atributo no válido)"
#DEFINE VFP_JSON_MSG_014 "Cadena JSON desequilibrada"
#DEFINE VFP_JSON_MSG_015 "La cadena JSON proporcionada no está bien formateada (nombre de variable no válido)"
#DEFINE VFP_JSON_MSG_016 "La cadena JSON proporcionada no representa un objeto de cursor válido"
#DEFINE VFP_JSON_MSG_017 "Parámetro que falta"
#DEFINE VFP_JSON_MSG_018 "Parámetro no válido"
#DEFINE VFP_JSON_MSG_019 "La cadena JSON suministrada no está bien formateada"
#DEFINE VFP_JSON_MSG_020 "El esquema está vacÃo"
#DEFINE VFP_JSON_MSG_021 "El JSON proporcionado no es un array de objetos"
#DEFINE VFP_JSON_MSG_022 "El alias ya existe"
#ENDIF
* Check for NQInclude utility (it will be downloaded if necessary).
checkForNQInclude()
* Check for dependencies
IF !FILE("vfplegacy.prg") OR !FILE("vfplegacy.h")
IF NOT NQInclude("vfplegacy")
CANCEL
ENDIF
MESSAGEBOX("This library requires VFPLEGACY.PRG library wich has been automatically downloaded. Please, erase JSON.FXP file and try again",48,"JSON.PRG")
CANCEL
ENDIF
#INCLUDE vfplegacy.h
* Load the library into mnemory
SET PROCEDURE TO json ADDITIVE
SET PROCEDURE TO vfplegacy ADDITIVE
PUBLIC json
json = CREATEOBJECT("json")
RETURN
* json (Class)
* JSON parser engine
*
DEFINE CLASS json AS Custom
version = 0 && Current version
useStrictNotation = .T. && Use JSON strict notation ("token" : value)
lastOpTime = 0 && Time (in seg) consumed by the last operation
Schemas = NULL && Published schemas
lastError = NULL && Last error info
stringSeparator = ["] && String separator
useFastParser = .F. && Use a faster parser (Non-VFP code)
HIDDEN oFastParser && Rerence to the fast parser
PROCEDURE version_access
RETURN 1.20
ENDPROC
* Init (Method)
* Constructor of Class
*
PROCEDURE Init()
* Add Property for handle of Cursors Schemas
THIS.Schemas = CREATEOBJECT("jsonSchemas")
* Add Property for handle of jSon Errors
THIS.lastError = CREATEOBJECT("jsonError")
* FastParser will be created first time is required
THIS.oFastParser = NULL
ENDPROC
* Parse (Method)
* Takes a JSON string and returns an object representation
*
* nMode variable can have following values:
* 0: Initial mode
* 1: Property mode
* 2: Value mode
* 3: Token complete mode
*
#IF VERSION(5) < 700
PROCEDURE Parse(pcJson, pnPos)
LOCAL nStarted, oJSON, oEX
nStarted = SECONDS()
ex = TRY()
IF THIS.useFastParser
oJSON = THIS._fastParse(pcJSON)
ELSE
oJSON = THIS._Parse(pcJson, pnPos)
ENDIF
IF CATCH(@ex)
THIS.lastError.initWithEx(ex)
oJSON = NULL
ENDIF
THIS.lastOpTime = SECONDS() - nStarted + IIF(SECONDS() < nStarted, 86400, 0)
RETURN oJSON
ENDPROC
#ENDIF
#IF VERSION(5) > 600
PROCEDURE Parse(pcJson, pnPos)
LOCAL nStarted, oJSON
nStarted = SECONDS()
TRY
IF THIS.useFastParser
oJSON = THIS._fastParse(pcJSON)
ELSE
oJSON = THIS._Parse(pcJson, pnPos)
ENDIF
CATCH TO ex
THIS.lastError.initWithEx(ex)
oJSON = NULL
ENDTRY
THIS.lastOpTime = SECONDS() - nStarted + IIF(SECONDS() < nStarted, 86400, 0)
RETURN oJSON
ENDPROC
#ENDIF
HIDDEN PROCEDURE _fastParse(pcJSON)
LOCAL oJS
oJS = THIS._getFastParser()
oJS.Language = "JScript"
pcJSON = ALLTRIM(CHRT(pcJSON, CHR(13) + CHR(10), ""))
RETURN oJS.Eval([(JSON.parse('] + pcJSON + ['))])
HIDDEN PROCEDURE _Parse(pcJSON, pnPos)
*
IF VARTYPE(pnPos) <> "N"
pcJSON = ALLTRIM(CHRT(pcJSON, CHR(13) + CHR(10), ""))
pnPos = 1
ENDIF
LOCAL i, nLen, cChar, cLastChar, nMode, cStringSep, lIsString, cProp, nNestLevel, oValue, ;
lExitLoop, oTarget, uBuff, lIsArray, oArray, lVarMode, lExprMode, nExprNestLevel, ;
nNestLevel
nLen = LEN(pcJSON)
cLastChar = CHR(0)
oTarget = NULL
cStringSep = THIS.stringSeparator
lIsString = .F.
nNestLevel = 0
lExitLoop = .F.
lIsArray = .F.
lVarMode = .F.
lExprMode = .F.
nExprNestLevel = 0
oArray = NULL
cChar = SUBSTR(pcJSON, pnPos, 1)
lIsArray = (cChar = "[")
oTarget = IIF(lIsArray, CREATEOBJECT("Collection"), CREATEOBJECT(_EMPTY))
nMode = IIF(lIsArray, 2, 0)
uBuff = ""
i = 1
THIS.lastError.hasError = .F.
#IF VERSION(5) > 600
TRY
#ENDIF
IF NOT cChar $ "[{" && A valid JSON string must start with { or [.
THROW(VFP_JSON_MSG_019)
ENDIF
nNestLevel = 1
FOR i = pnPos + 1 TO nLen
*
cChar = SUBSTR(pcJSON, i, 1)
DO CASE
CASE cChar $ CHR(9) && Ignorable chars
LOOP
CASE cChar = "{" AND !lIsString && Start new object
uBuff = THIS._Parse(pcJSON, @i)
nMode = 3
CASE cChar $ "}]" AND !lIsString && Close last object or array
lExitLoop = .T.
nMode = IIF(INLIST(cLastChar,cStringSep,"{","[") OR (EMPTY(cProp) AND (!lIsArray OR EMPTY(uBuff))), nMode, 3)
nNestLevel = nNestLevel - 1
CASE cChar = "[" AND !lIsString && Start new array
uBuff = THIS._Parse(pcJSON, @i)
nMode = 3
CASE cChar = cStringSep AND nMode = 0 && Property name start
nMode = 1
uBuff = ""
CASE nMode = 0 AND THIS.isAlpha(cChar) && Property name start (non-quoted property)
nMode = 1
uBuff = cChar
CASE nMode = 1 AND !THIS.isAlpha(cChar) AND !ISDIGIT(cChar) AND !INLIST(cChar,":",SPACE(1),cStringSep,"-") && Invalid char in property mode
THROW(VFP_JSON_MSG_013 + " (" + SUBSTR(pcJSON, i - 10, 10) + " -->" + cChar + "<-- " + SUBSTR(pcJSON,i+1,20) + ") " + TRANSFORM(lIsString,"") + " " + TRANSFORM(uBuff,""))
CASE !INLIST(cChar, cStringSep, ":", SPACE(1)) AND nMode = 1 && Property name
uBuff = uBuff + CHRTRAN(cChar,"-","_")
CASE cChar = ":" AND nMode = 1 && Close property name
cProp = ALLTRIM(uBuff)
uBuff = ""
nMode = 2
lIsString = .F.
lExprMode = .F.
lVarMode = .F.
IF cProp = "codlts"
*SET STEP ON
ENDIF
CASE cChar = SPACE(1) AND nMode = 2 AND !lIsString && Discard spaces between property name and property value
CASE nMode = 2 AND !lIsString AND EMPTY(uBuff) AND THIS.isAlpha(cChar) && Variable value start
uBuff = uBuff + cChar
lVarMode = .T.
lIsString = .T.
CASE nMode = 2 AND lVarMode AND !EMPTY(uBuff) AND INLIST(cChar,[ ],[,],"]","}") && Variable value end
lVarMode = .F.
DO CASE
CASE INLIST(LOWER(uBuff),"true","false")
uBuff = (LOWER(uBuff) == "true")
CASE LOWER(uBuff) == "null"
uBuff = null
OTHERWISE
_TRY
uBuff = EVALUATE(uBuff)
_CATCH
uBuff = ex.Message
_ENDTRY
ENDCASE
nMode = 3
lIsString = (VARTYPE(uBuff) = "C")
IF cChar $ "]}"
nNestLevel = nNestLevel - 1
lExitLoop = .T.
ENDIF
CASE nMode = 2 AND lVarMode AND !EMPTY(uBuff) AND !THIS.isAlpha(cChar) AND !INLIST(cChar,[ ],[,],"]","}") && Invalid variable char
THROW(VFP_JSON_MSG_015 + " (" + SUBSTR(pcJSON, i - 10, 10) + " -->" + cChar + "<-- " + SUBSTR(pcJSON,i+1,20) + ")")
CASE nMode = 2 AND !lExprMode AND EMPTY(uBuff) AND cChar = "(" AND !lIsString && Expresion value start
lExprMode = .T.
uBuff = ""
lIsString = .T.
nExprNestLevel = 1
CASE nMode = 2 AND lExprMode AND cChar = "("
nExprNestLevel = nExprNestLevel + 1
uBuff = uBuff + cChar
CASE nMode = 2 AND lExprMode AND cChar = ")" AND nExprNestLevel > 1
nExprNestLevel = nExprNestLevel - 1
uBuff = uBuff + cChar
CASE nMode = 2 AND lExprMode AND cChar = ")" AND nExprNestLevel = 1 && Expresion value end
lExprMode = .F.
nExprNestLevel = 0
_TRY
uBuff = STRT(uBuff, "this.", "oTarget.")
uBuff = STRT(uBuff, "THIS.", "oTarget.")
uBuff = STRT(uBuff, "This.", "oTarget.")
uBuff = EVALUATE(uBuff)
IF NOEX()
lIsString = (VARTYPE(uBuff) $ "CM")
ENDIF
_CATCH
uBuff = ex.Message
_ENDTRY
nMode = 3
CASE nMode = 2 AND lExprMode
uBuff = uBuff + cChar
CASE cChar = cStringSep AND !lIsString AND nMode = 2 && String value start
lIsString = .T.
CASE cChar = cStringSep AND lIsString AND nMode = 2 AND cLastChar<>"\" && End string value
nMode = 3
CASE cChar = "," AND !lIsString AND nMode = 2 && End non-string value
nMode = IIF(INLIST(cLastChar,cStringSep,"{","["), nMode, 3)
*!*
*!* CASE nMode = 2
*!* uBuff = uBuff + cChar
CASE nMode = 2
uBuff = uBuff + cChar
IF cChar = "\" AND cChar = cLastChar && Avoid an parsing error when last char in string is "\\"
cChar = CHR(0)
ENDIF
ENDCASE
IF nMode = 3
DO CASE
CASE !VARTYPE(uBuff) $ "COX"
CASE lIsString
lIsString = .F.
DO CASE
CASE LIKE("????-??-??T??:??:??",uBuff)
uBuff = CTOT("^" + uBuff)
CASE LIKE("????-??-??",uBuff)
uBuff = CTOD("^" + uBuff)
OTHERWISE
uBuff = THIS.unescapeHTML(uBuff)
ENDCASE
CASE VARTYPE(uBuff) = "O"
CASE VARTYPE(uBuff) = "X" OR LOWER(uBuff) == "null"
uBuff = NULL
CASE LOWER(uBuff) == "false"
uBuff = .F.
CASE LOWER(uBuff) == "true"
uBuff = .T.
OTHERWISE
uBuff = IIF(AT(".",uBuff) = 0, INT(VAL(uBuff)), VAL(uBuff))
ENDCASE
IF lIsArray
oTarget.Add(uBuff)
uBuff = ""
nMode = 2
ELSE
IF !EMPTY(cProp)
ADDPROPERTY(oTarget, cProp, uBuff)
ENDIF
nMode = 0
cProp = ""
uBuff = ""
ENDIF
ENDIF
IF lExitLoop
EXIT
ENDIF
cLastChar = cChar
*
ENDFOR
pnPos = i
IF nNestLevel <> 0
THROW(VFP_JSON_MSG_014)
ENDIF
#IF VERSION(5) > 600
CATCH TO ex
ex.Details = STUFF(pcJSON,i,6,cChar + "<-- ") &&+ " [Mode: " + ALLTRIM(STR(nMode)) + ", uBuff: " + TRANSFORM(uBuff,"") + ", cProp: " + cProp + "]"
THIS.lastError.initWithEx(ex)
oTarget = NULL
ENDTRY
#ENDIF
RETURN oTarget
*
ENDPROC
* parseCursor (Method)
* Takes a JSON string and recreate the original cursor
*
PROCEDURE parseCursor(pcJSON, pcAlias, pnDSID)
*
LOCAL oCursor,nStarted
nStarted = SECONDS()
oCursor = THIS.Parse(pcJSON)
IF THIS.lastError.hasError
RETURN .F.
ENDIF
IF !PEMSTATUS(oCursor, "schema", 5)
THIS.lastError.initWithString(VFP_JSON_MSG_016)
RETURN .F.
ENDIF
IF PEMSTATUS(oCursor, "name", 5)
pcAlias = EVL(pcAlias, oCursor.name)
ENDIF
IF !EMPTY(pnDSID)
SET DATASESSION TO (pnDSID)
ENDIF
IF EMPTY(pcAlias)
DO WHILE .T.
pcAlias = "Q" + SYS(2015)
IF !USED(pcAlias)
EXIT
ENDIF
ENDDO
ENDIF
LOCAL oSchema
oSchema = CREATEOBJECT("jsonSchema")
IF NOT oSchema.initWithJSON(oCursor)
THIS.lastOpTime = SECONDS() - nStarted + IIF(SECONDS() < nStarted, 86400, 0)
RETURN .F.
ENDIF
SELECT 0
IF NOT oSchema.toCursor(pcAlias)
THIS.lastOpTime = SECONDS() - nStarted + IIF(SECONDS() < nStarted, 86400, 0)
RETURN .F.
ENDIF
IF PEMSTATUS(oCursor, "rows", 5)
LOCAL oRow, i, nCount
nCount = oCursor.Rows.Count
SELECT (pcAlias)
FOR i = 1 TO nCount
oRow = oCursor.Rows.Item[i]
APPEND BLANK
GATHER NAME oRow MEMO
ENDFOR
GO TOP
ENDIF
THIS.lastOpTime = SECONDS() - nStarted + IIF(SECONDS() < nStarted, 86400, 0)
*
ENDPROC
* parseXML (Method)
* Takes an XML string and returns an object representation
*
FUNCTION parseXML(poXmlNode, pcArrayNodes)
*
IF VARTYPE(poXmlNode) = "C"
LOCAL oXml
oXml = CREATEOBJECT('msxml.domdocument')
oXml.loadXML(poXmlNode)
poXmlNode = oXml
ENDIF
LOCAL oTarget,i
oTarget = CREATEOBJECT(_EMPTY)
IF VARTYPE(pcArrayNodes)<>"C"
pcArrayNodes = ""
ENDIF
* Add any attribute the node has
IF TYPE("poXmlNode.Attributes.Length")="N"
LOCAL cAttr, oAttr
FOR i = 1 TO poXmlNode.Attributes.Length
oAttr = poXmlNode.Attributes.Item[i-1]
cAttr = CHRTRAN(oAttr.Name,":-","_")
ADDPROPERTY(oTarget, cAttr, oAttr.Value)
ENDFOR
ENDIF
* Get a child list
LOCAL oNode,cChildName,lIsArray,oChilds,nChilds,nGrandChilds
oChilds = CREATEOBJECT("Collection")
DO CASE
CASE TYPE("poXmlNode.childNodes.Length") = "N"
FOR i = 1 TO poXmlNode.childNodes.Length
oChilds.Add(poXmlNode.childNodes.Item[i - 1])
ENDFOR
CASE TYPE("poXmlNode.Length") = "N"
FOR i = 1 TO poXmlNode.Length
oChilds.Add(poXmlNode.Item[i - 1])
ENDFOR
ENDCASE
* If the node has no childs, we don't need to do anything else
nChilds = oChilds.Count
IF nChilds = 0
RETURN oTarget
ENDIF
* If all children has the same name, handle this node as a collection
IF nChilds > 1
cChildName = oChilds.Item[1].nodeName
lIsArray = .T.
FOR i = 1 TO nChilds
IF !(oChilds.Item[i].nodeName == cChildName)
lIsArray = .F.
EXIT
ENDIF
ENDFOR
ENDIF
IF lIsArray
oTarget = CREATEOBJECT("Collection")
ENDIF
* Handle node's children
LOCAL cNodeName,cData,cLastNode,oLastNode,oArray,uData
oLastNode = NULL
cLastNode = ""
FOR i = 1 TO nChilds
oNode = oChilds.Item[i]
nGrandChilds = oNode.childNodes.Length
cNodeName = CHRTRAN(oNode.nodeName, ":-", "_")
DO CASE
CASE nGrandChilds = 0 AND oNode.Attributes.Length = 0
ADDPROPERTY(oTarget, cNodeName, "")
CASE nGrandChilds = 1 AND INLIST(oNode.childNodes.Item[0].nodeName,"#text","#cdata-section")
cData = oNode.childNodes.Item[0].Data
uData = cData
DO CASE
CASE LIKE("????-??-??T??:??:??",cData) && Date, Date/Time
uData = CTOT(cData)
IF !EMPTY(uData)
IF HOUR(uData) = 0 AND MINUTE(uData) = 0 AND SEC(uData) = 0
uData = TTOD(uData)
ENDIF
ELSE
uData = cData
ENDIF
CASE INLIST(LOWER(cData),"true","false") && Boolean
uData = (LOWER(cData) == "true")
CASE INLIST(LOWER(cData),"null","nil") && Null value
uData = NULL
CASE AT(".",cData) > 0 AND VAL(cData) > 0 && Numeric value (not INT)
uData = VAL(cData)
ENDCASE
ADDPROPERTY(oTarget, cNodeName, uData)
CASE lIsArray
oTarget.Add(THIS.parseXml(oNode, pcArrayNodes))
CASE cNodeName == cLastNode
IF TYPE("oLastNode.Class")<>"C" OR LOWER(oLastNode.class) <> "collection"
oArray = CREATEOBJECT("Collection")
oArray.Add(oLastNode)
STORE oArray TO ("oTarget." + cNodeName)
oLastNode = GETPEM(oTarget, cNodeName)
ENDIF
oLastNode.Add(THIS.parseXml(oNode, pcArrayNodes))
OTHERWISE
ADDPROPERTY(oTarget, cNodeName, THIS.parseXml(oNode, pcArrayNodes))
oLastNode = GETPEM(oTarget, cNodeName)
cLastNode = cNodeName
ENDCASE
ENDFOR
RETURN oTarget
ENDPROC
* parseArray
* Toma un array y devuelve un objeto tipo JSON
*
PROCEDURE parseArray(paList)
EXTERNAL ARRAY paList
LOCAL oTarget,i,nRows,nCols,j,oItem
nRows = ALEN(paList,1)
nCols = ALEN(paList,2)
oTarget = CREATE("Collection")
FOR i = 1 TO nRows
IF nCols <= 1
oTarget.Add(paList[i])
ELSE
oItem = CREATEOBJECT("Collection")
FOR j = 1 TO nCols
oITem.Add(paList[i,j])
ENDFOR
oTarget.Add(oItem)
ENDIF
ENDFOR
RETURN oTarget
ENDPROC
* Stringify (Method)
* Takes an object or alias and returns a JSON string representation
*
* Usage: jsonString = oJSON.Stringify(object)
* jsonString = oJSON.Stringify("alias" [,plWithSchema] [,pnDataSessionID] [,pcAdditionalFields])
* jsonString = oJSON.Stringify(@array)
*
PROCEDURE Stringify(puObjectOrAlias, plWithSchema, pnDSID, pcAdditionalFields, plValueMode)
*
LOCAL cJSON,cType,oRow,nWkArea,nRow,nCount,i,j,cProp,uValue,cValue,cValueType,nColumns,cTokenSep,nStarted
LOCAL ARRAY aProps[1]
cJSON = ""
nWkArea = SELECT()
cType = VARTYPE(puObjectOrAlias)
nStarted = SECONDS()
IF !EMPTY(pnDSID)
SET DATASESSION TO (pnDSID)
ENDIF
* Check if value passed is an array. An array is:
* a) An object with a baseClass equal to "Collection" and a Count property [1]
* b) An array
*
* [1] The Count property verification is required to avoid an error when stringifing SCX files as cursors, because SCX
* doesn contains a BASECLASS column and could contains Collection objets, wich would be wrongly tested as "array".
LOCAL lIsArray
lIsArray = ((cType = "O" AND PEMSTATUS(puObjectOrAlias,"baseClass",5) AND ;
PEMSTATUS(puObjectOrAlias, "Count", 5) AND ;
PEMSTATUS(puObjectOrAlias, "Item", 5) AND ;
LOWER(puObjectOrAlias.baseClass) == "collection") OR ;
(TYPE("ALEN(puObjectOrAlias)") = "N"))
* Checkl if value passed is a JS object
LOCAL lIsJSObject
lIsJSObject = .F.
IF cType = "O"
lIsJSObject = (AMEMBERS(aProps, puObjectOrAlias, 0) = 0)
ENDIF
DO CASE
CASE cType = "O" AND lIsJSObject && JSObject
LOCAL oJS
oJS = THIS._getFastParser(.T.)
oJS.addObject("obj",puObjectOrAlias)
RETURN oJS.Eval([(JSON.stringify(obj))])
CASE cType = "O" AND !lIsArray && Object
nCount = AMEMBERS(aProps,puObjectOrAlias,1)
#IF VERSION(5) < 800
LOCAL lEmptyObject,oLine
lEmptyObject = (TYPE("puObjectOrAlias.Class")="C" AND LOWER(puObjectOrAlias.Class) == "emptyobject")
IF lEmptyObject
oLine = CREATE("Line")
ENDIF
#ENDIF
FOR i = 1 TO nCount
IF aProps[i,2] <> "Property"
LOOP
ENDIF
cProp = LOWER(aProps[i,1])
IF "-"+LOWER(cProp)+"-" $ VFP_NOENCODABLE_PROPS
LOOP
ENDIF
#IF VERSION(5) < 800
IF lEmptyObject AND PEMSTATUS(oLine, cProp, 5)
LOOP
ENDIF
#ENDIF
uValue = GETPEM(puObjectOrAlias, cProp)
cValue = THIS.Stringify(uValue,,,,.T.)
IF !ISNULL(cValue)
IF THIS.useStrictNotation
cProp = ["] + cProp + ["]
ENDIF
cJSON = cJSON + IIF(EMPTY(cJSON),"",", ") + cProp + [ : ] + cValue
ENDIF
ENDFOR
cJSON = "{" + cJSON + "}"
CASE cType = "O" AND lIsArray && Array (Collection)
cJSON = "["
FOR i = 1 TO puObjectOrAlias.Count
cJSON = cJSON + IIF(i > 1,",","") + THIS.Stringify(puObjectOrAlias.Item[i],,,,.T.)
ENDFOR
cJSON = cJSON + "]"
CASE cType<>"O" AND lIsArray && Array
EXTERNAL ARRAY puObjectOrAlias
nColumns = MAX(ALEN(puObjectOrAlias, 2), 1) && Because a one dimension array returns 0 for ALEN(2)
cJSON = "["
FOR i = 1 TO ALEN(puObjectOrAlias,1)
cJSON = cJSON + IIF(i > 1,",","")
IF nColumns = 1
cJSON = cJSON + THIS.Stringify(puObjectOrAlias[i],,,,.T.)
ELSE
cJSON = cJSON + "["
FOR j = 1 TO nColumns
cJSON = cJSON + IIF(j > 1,",","") + THIS.Stringify(puObjectOrAlias[i,j], .T.)
ENDFOR
cJSON = cJSON + "]"
ENDIF
ENDFOR
cJSON = cJSON + "]"
CASE cType = "C" AND USED(puObjectOrAlias) AND !plValueMode && Cursor
cJSON = [{"name" : "] + puObjectOrAlias + [", "rows" : ] + "["
*cJSON = [{"name" = "] + puObjectOrAlias + [", "rows" = ] + "["
IF !EMPTY(pnDSID)
SET DATASESSION TO (pnDSID)
ENDIF
SELECT (puObjectOrAlias)
GO TOP
nRow = 0
SCAN
nRow = nRow + 1
SCATTER NAME oRow MEMO
cJSON = cJSON + IIF(nRow > 1,",","") + THIS.Stringify(oRow)
ENDSCAN
cJSON = cJSON + "]"
IF plWithSchema
LOCAL oSchema
oSchema = CREATEOBJECT("jsonSchema")
oSchema.initWithAlias(puObjectOrAlias)
cProp = "schema"
IF THIS.useStrictNotation
cProp = ["] + cProp + ["]
ENDIF
cJSON = cJSON + [, ] + cProp + [ : ] + oSchema.toString(.T.)
ENDIF
IF !EMPTY(pcAdditionalFields)
cJSON = cJSON + [, ] + pcAdditionalFields
ENDIF
cJSON = cJSON + [}]
OTHERWISE && Scalar value
uValue = puObjectOrAlias
cValueType = VARTYPE(uValue)
DO CASE
CASE cValueType $ "CM"
cValue = ["] + THIS.escapeHTML(RTRIM(uValue)) + ["]
CASE cValueType $ "NIYF"
IF INT(uValue) = uValue
cValue = ALLTRIM(STR(uValue))
ELSE
cValue = ALLTRIM(STR(uValue,30,10))
DO WHILE RAT("0", cValue) = LEN(cValue)
cValue = SUBSTR(cValue, 1, LEN(cValue) - 1)
ENDDO
ENDIF
cValue = CHRTRAN(cValue, SET("POINT"), ".")
CASE cValueType = "D"
cValue = ["] + PADL(YEAR(uValue),4,"0") + "-" + PADL(MONTH(uValue),2,"0") + "-" + PADL(DAY(uValue),2,"0") + ["]
CASE cValueType = "T"
cValue = ["] + PADL(YEAR(uValue),4,"0") + "-" + PADL(MONTH(uValue),2,"0") + "-" + PADL(DAY(uValue),2,"0") + ;
[T] + PADL(HOUR(uValue),2,"0") + ":" + PADL(MINUTE(uValue),2,"0") + ":" + PADL(SEC(uValue),2,"0") + ["]
CASE cValueType = "L"
cValue = IIF(uValue,"true","false")
CASE cValueType = "X"
cValue = "null"
OTHERWISE
cValue = NULL
ENDCASE
cJSON = cValue
ENDCASE
THIS.lastOpTime = SECONDS() - nStarted + IIF(SECONDS() < nStarted, 86400, 0)
SELECT (nWkArea)
RETURN cJSON
*
ENDPROC
* Beautify (Method)
* Takes a JSON object or string and returns a formatted
* string representation
*
PROCEDURE Beautify(puData, pcOut, pnMargin, pcAttr)
*
LOCAL nStarted
nStarted = SECONDS()
IF VARTYPE(puData)="C" AND LEFT(puData,1) $ "{[" AND PCOUNT() = 1
puData = THIS.Parse(puData)
ENDIF
IF EMPTY(pcOut)
pcOut = ""
ENDIF
IF EMPTY(pnMargin)
pnMArgin = LEN(MLINE(pcOut, MEMLINES(pcOUt)))
ENDIF
LOCAL cType
cType = VARTYPE(puData)
pcOut = pcOut + SPACE(pnMargin)