jsondoc.pas

jsondoc.pas

功能:bson序列、还原

开源地址:

https://github.com/stijnsanders/TMongoWire

编程接口:

1
2
3
4
5
6
7
8
9
10
11
12
13
IJSONDocument = interface(IUnknown)
  ['{4A534F4E-0001-0001-C000-000000000001}']
  function Get_Item(const Key: WideString): Variant; stdcall;
  procedure Set_Item(const Key: WideString; const Value: Variant); stdcall;
  procedure Parse(const JSONData: WideString); stdcall;
  function ToString: WideString; stdcall;
  function ToVarArray: Variant; stdcall;
  procedure Clear; stdcall;
  procedure Delete(const Key: WideString); stdcall;
  property Item[const Key: WideString]: Variant
    read Get_Item write Set_Item; default;
  property AsString: WideString read ToString write Parse;
end;

  

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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
{
 
jsonDoc.pas
 
Copyright 2015-2019 Stijn Sanders
Made available under terms described in file "LICENSE"
https://github.com/stijnsanders/jsonDoc
 
v1.2.0
 
}
unit jsonDoc;
 
{$WARN SYMBOL_PLATFORM OFF}
{$D-}
{$L-}
 
{
 
Options:
Define here or in the project settings
 
  JSONDOC_JSON_STRICT
    to disallow missing quotes around key names
 
  JSONDOC_JSON_LOOSE
    to allow missing colons and comma's
 
  JSONDOC_JSON_PASCAL_STRINGS
    to allow pascal-style strings
 
  JSONDOC_P2
    to combine JSONDOC_JSON_LOOSE and JSONDOC_JSON_PASCAL_STRINGS
 
  JSONDOC_STOREINDENTING
    to make ToString write indentation EOL's and tabs
 
  JSONDOC_THREADSAFE
    to make IJSONDocument instances thread-safe
 
  JSONDOC_DEFAULT_USE_IJSONARRAY
    to set JSON_UseIJSONArray to true by default
 
}
 
interface
 
uses SysUtils;
 
const
  //COM GUID's
  IID_IJSONDocument
    : TGUID = '{4A534F4E-0001-0001-C000-000000000001}';
  CLASS_JSONDocument
    : TGUID = '{4A534F4E-0001-0002-C000-000000000002}';
  IID_IJSONEnumerator
    : TGUID = '{4A534F4E-0001-0003-C000-000000000003}';
  IID_IJSONEnumerable
    : TGUID = '{4A534F4E-0001-0004-C000-000000000004}';
  IID_IJSONArray
    : TGUID = '{4A534F4E-0001-0005-C000-000000000005}';
  IID_IJSONDocArray
    : TGUID = '{4A534F4E-0001-0006-C000-000000000006}';
  IID_IJSONDocWithReUse
    : TGUID = '{4A534F4E-0001-0007-C000-000000000007}';
 
type
{
  IJSONDocument interface
  the base JSON document interface that provides access to a set of
  key-value pairs.
  use AsString and Parse to convert JSON to and from string values.
  use AsVarArray to access the key-value pairs as a [x,2] variant array.
  use Clear to re-use a JSON doc for parsing or building a new similar
  document and keep the allocated memory for keys and values.
  see also: JSON function
}
  IJSONDocument = interface(IUnknown)
    ['{4A534F4E-0001-0001-C000-000000000001}']
    function Get_Item(const Key: WideString): Variant; stdcall;
    procedure Set_Item(const Key: WideString; const Value: Variant); stdcall;
    procedure Parse(const JSONData: WideString); stdcall;
    function ToString: WideString; stdcall;
    function ToVarArray: Variant; stdcall;
    procedure Clear; stdcall;
    procedure Delete(const Key: WideString); stdcall;
    property Item[const Key: WideString]: Variant
      read Get_Item write Set_Item; default;
    property AsString: WideString read ToString write Parse;
  end;
 
{
  IJSONEnumerator interface
  use IJSONEnumerator to enumerate a document's key-value pairs
  see also: JSONEnum function
}
  //TODO: IEnumVariant?
  IJSONEnumerator = interface(IUnknown)
    ['{4A534F4E-0001-0003-C000-000000000003}']
    function EOF: boolean; stdcall;
    function Next: boolean; stdcall;
    function Get_Key: WideString; stdcall;
    function Get_Value: Variant; stdcall;
    procedure Set_Value(const Value: Variant); stdcall;
    function v0: pointer; stdcall;
    property Key: WideString read Get_Key;
    property Value: Variant read Get_Value write Set_Value;
  end;
 
{
  IJSONEnumerable interface
  used to get a IJSONEnumerable instance for a document
  see also: JSONEnum function
}
  IJSONEnumerable = interface(IUnknown)
    ['{4A534F4E-0001-0004-C000-000000000004}']
    function NewEnumerator: IJSONEnumerator; stdcall;
  end;
 
{
  IJSONArray interface
  When using VarArrayOf (declared in Variants.pas), a SafeArray is
  used internally for storage, but as a variant value VarCopy is called
  with each use, creating duplicate (deep) copies of the SafeArray.
  Use IJSONArray (and the ja function) to create a IJSONArray instance
  that uses a single copy of the data. It is also reference counted,
  which automates memory clean-up.
}
  IJSONArray = interface(IUnknown)
    ['{4A534F4E-0001-0005-C000-000000000005}']
    function Get_Item(Index: integer): Variant; stdcall;
    procedure Set_Item(Index: integer; const Value: Variant); stdcall;
    function Count: integer; stdcall;
    function ToString: WideString; stdcall;
    function v0(Index: integer): pointer; stdcall;
    property Item[Idx: integer]: Variant read Get_Item write Set_Item; default;
  end;
 
{
  IJSONDocArray interface
  use IJSONDocArray to build an array of similar documents,
  ideally in combination with a single IJSONDocument instance and
  IJSONDocument.Clear to re-use the memory allocated for keys and values
  see also: JSONDocArr function
}
  IJSONDocArray = interface(IJSONArray)
    ['{4A534F4E-0001-0006-C000-000000000006}']
    function Add(const Doc: IJSONDocument): integer; stdcall;
    function AddJSON(const Data: WideString): integer; stdcall;
    procedure LoadItem(Index: integer; const Doc: IJSONDocument); stdcall;
    procedure Clear; stdcall;
    function GetJSON(Index: integer): WideString; stdcall;
  end;
 
{
  IJSONDocWithReUse interface
  used internally to enable re-use of allocated keys
  see also: TJSONDocument Parse and Clear
}
  IJSONDocWithReUse = interface(IUnknown)
    ['{4A534F4E-0001-0007-C000-000000000007}']
    function ReUse(const Key: WideString): Variant; stdcall;
  end;
 
{
  JSON function: JSON document factory
  call JSON without parameters do create a new blank document
}
function JSON: IJSONDocument; overload;
 
{
  JSON function: JSON document builder
  pass an array of alternately keys and values,
  suffix key with opening brace to start an embedded document,
  and key of a single closing brace to close it.
}
function JSON(const x: array of Variant): IJSONDocument; overload;
 
{
  JSON function: JSON document converter
  pass a single variant to have it converted to an IJSONDocument interface
  or a string with JSON parsed into a IJSONDocument
  or nil when VarIsNull
}
function JSON(const x: Variant): IJSONDocument; overload;
 
{
  JSONEnum function
  get a new enumerator to enumeratare the key-value pairs in the document
}
function JSONEnum(const x: IJSONDocument): IJSONEnumerator; overload; //inline;
function JSONEnum(const x: Variant): IJSONEnumerator; overload;
function JSON(const x: IJSONEnumerator): IJSONDocument; overload; //inline;
function JSONEnum(const x: IJSONEnumerator): IJSONEnumerator; overload; //inline;
 
{
  ja function
  create and populate a new IJSONArray instance
  or cast a Variant holding a JSONArray instance to the interface reference
}
function ja(const Items:array of Variant): IJSONArray; overload;
function ja(const Item:Variant): IJSONArray; overload;
 
{
  JSONDocArray function
  get a new IJSONDocArray instance
}
function JSONDocArray: IJSONDocArray; overload;
function JSONDocArray(const Items:array of IJSONDocument): IJSONDocArray; overload;
 
 
{
  JSON_UseIJSONArray
  switch JSON so it will create IJSONArray instances to hold arrays of values
  instead of VarArrayCreate, default false
  see also TJSONDocument.UseIJSONArray property
}
var
  JSON_UseIJSONArray: boolean;
 
{
  TJSONImplBaseObj
  common base object JSON implementation objects inherit
  don't use directly
}
type
 
{$IFDEF JSONDOC_THREADSAFE}
  TJSONImplBaseObj = class(TInterfacedObject)
  protected
    FLock:TRTLCriticalSection;
  public
    procedure AfterConstruction; override;
    destructor Destroy; override;
  end;
 
{$ELSE}
  //thread-unsafe anyway, so avoid locking when reference counting:
  TJSONImplBaseObj = class(TObject, IInterface)
  protected
    FRefCount: Integer;
    function QueryInterface(const IID: TGUID; out Obj): HResult; stdcall;
    function _AddRef: Integer; stdcall;
    function _Release: Integer; stdcall;
  public
    procedure AfterConstruction; override;
    procedure BeforeDestruction; override;
    class function NewInstance: TObject; override;
    property RefCount: Integer read FRefCount;
  end;
 
{$ENDIF}
 
{
  TJSONDocument class
  the default IJSONDocument implementation
  see also: JSON function
}
  TJSONDocument = class(TJSONImplBaseObj, IJSONDocument, IJSONEnumerable,
    IJSONDocWithReUse)
  private
    FElementIndex,FElementSize:integer;
    FElements:array of record
      SortIndex,LoadIndex:integer;
      Key:WideString;
      Value:Variant;
    end;
    FLoadIndex:integer;
    {$IFNDEF JSONDOC_THREADSAFE}
    FGotIndex,FGotSorted:integer;
    FGotMatch:boolean;
    {$ENDIF}
    FUseIJSONArray:boolean;
    function GetKeyIndex(const Key: WideString;
      var GotIndex: integer; var GotSorted: integer): boolean;
  protected
    function Get_Item(const Key: WideString): Variant; stdcall;
    procedure Set_Item(const Key: WideString; const Value: Variant); stdcall;
    function ReUse(const Key: WideString): Variant; stdcall;
  public
    procedure AfterConstruction; override;
    destructor Destroy; override;
    procedure Parse(const JSONData: WideString); stdcall;
    function JSONToString: WideString; stdcall;
    function IJSONDocument.ToString=JSONToString;
    function ToVarArray: Variant; stdcall;
    procedure Clear; stdcall;
    function NewEnumerator: IJSONEnumerator; stdcall;
    procedure Delete(const Key: WideString); stdcall;
    property Item[const Key: WideString]: Variant
      read Get_Item write Set_Item; default;
    property AsString: WideString read JSONToString write Parse;
    property UseIJSONArray:boolean read FUseIJSONArray write FUseIJSONArray;
  end;
 
{
  TJSONEnumerator class
  the default IJSONEnumerator implementation
  see also: JSONEnum function
}
  TJSONEnumerator = class(TJSONImplBaseObj, IJSONEnumerator)
  private
    FData:TJSONDocument;
    FIndex: integer;
  public
    constructor Create(Data: TJSONDocument);
    destructor Destroy; override;
    function EOF: boolean; stdcall;
    function Next: boolean; stdcall;
    function Get_Key: WideString; stdcall;
    function Get_Value: Variant; stdcall;
    procedure Set_Value(const Value: Variant); stdcall;
    function v0: pointer; stdcall;
  end;
 
{
  TJSONArray class
  Default ILightArray implementation
}
  TJSONArray = class(TJSONImplBaseObj, IJSONArray, IJSONEnumerable)
  private
    FData:array of Variant;
  protected
    function Get_Item(Index: integer): Variant; stdcall;
    procedure Set_Item(Index: integer; const Value: Variant); stdcall;
    function Count: integer; stdcall;
    function JSONToString: WideString; stdcall;
    function IJSONArray.ToString=JSONToString;
    function v0(Index: integer): pointer; stdcall;
    function NewEnumerator: IJSONEnumerator; stdcall;
  public
    constructor Create(Size: integer);
  end;
 
{
  TJSONArrayEnumerator
  an IJSONEnumerator implementation that iterates over a variant array
  used internally to convert to JSON
}
  TJSONArrayEnumerator= class(TJSONImplBaseObj, IJSONEnumerator)
  private
    FData:IJSONArray;
    FIndex,FMax:integer;
  public
    constructor Create(const Data:IJSONArray);
    destructor Destroy; override;
    function EOF: boolean; stdcall;
    function Next: boolean; stdcall;
    function Get_Key: WideString; stdcall;
    function Get_Value: Variant; stdcall;
    procedure Set_Value(const Value: Variant); stdcall;
    function v0: pointer; stdcall;
  end;
 
{
  TJSONDocArray class
  the default IJSONDocArray implementation
  see also: JSONDocArray function
}
  TJSONDocArray = class(TJSONImplBaseObj, IJSONArray, IJSONDocArray)
  private
    FItems:array of WideString;
    FItemsCount,FItemsSize,FCurrentIndex:integer;
    FCurrent:Variant;
  protected
    //IJSONArray
    function Get_Item(Index: integer): Variant; stdcall;
    procedure Set_Item(Index: integer; const Value: Variant); stdcall;
    function Count: integer; stdcall;
    function JSONToString: WideString; stdcall;
    function IJSONArray.ToString=JSONToString;
    function v0(Index: integer): pointer; stdcall;
    //function IJSONArray.ToString=JSONToString;
    //IJSONDocArray
    function Add(const Doc: IJSONDocument): integer; stdcall;
    function AddJSON(const Data: WideString): integer; stdcall;
    procedure LoadItem(Index: integer; const Doc: IJSONDocument); stdcall;
    function IJSONDocArray.ToString=JSONToString;
    procedure Clear; stdcall;
    function GetJSON(Index: integer): WideString; stdcall;
  public
    constructor Create;
    destructor Destroy; override;
  end;
 
{
  TVarArrayEnumerator
  an IJSONEnumerator implementation that iterates over a variant array
  used internally to convert to JSON
}
  TVarArrayEnumerator = class(TJSONImplBaseObj, IJSONEnumerator)
  private
    FData:PVariant;
    FCurrent:Variant;
    FIndex,FMax,FCurrentIndex:integer;
  public
    constructor Create(const Data:PVariant);
    destructor Destroy; override;
    function EOF: boolean; stdcall;
    function Next: boolean; stdcall;
    function Get_Key: WideString; stdcall;
    function Get_Value: Variant; stdcall;
    procedure Set_Value(const Value: Variant); stdcall;
    function v0: pointer; stdcall;
  end;
 
{
  TVarJSONArray
  an IJSONArray implementation that works on an existing variant array
  used internally by the ja function
}
  TVarJSONArray = class(TJSONImplBaseObj, IJSONArray)
  private
    FData,FCurrent:Variant;
    v1,v2,FCurrentIndex:integer;
  protected
    function Get_Item(Index: integer): Variant; stdcall;
    procedure Set_Item(Index: integer; const Value: Variant); stdcall;
    function Count: integer; stdcall;
    function JSONToString: WideString; stdcall;
    function IJSONArray.ToString=JSONToString;
    function v0(Index: integer): pointer; stdcall;
  public
    constructor Create(const Data: Variant);
    constructor CreateNoCopy(var Data: Variant);
    destructor Destroy; override;
  end;
 
{
  EJSONException class types
  exception types thrown from TJSONDocument's Parse and ToString
}
  EJSONException=class(Exception);
  EJSONDecodeException=class(EJSONException);
  EJSONEncodeException=class(EJSONException);
 
 
implementation
 
uses Variants{, Windows}; //cxg
 
procedure VarMove(var Dest, Src: Variant);
begin
  //Dest:=Src;VarClear(Src);
  Move(Src,Dest,SizeOf(TVarData));
  FillChar(src, SizeOf(TVarData), 0);  //cxg
  //ZeroMemory(@Src,SizeOf(TVarData));
end;
 
{ TJSONImplBaseObj }
 
{$IFDEF JSONDOC_THREADSAFE}
 
procedure TJSONImplBaseObj.AfterConstruction;
begin
  inherited;
  InitializeCriticalSection(FLock);
end;
 
destructor TJSONImplBaseObj.Destroy;
begin
  DeleteCriticalSection(FLock);
  inherited;
end;
 
{$ELSE}
 
procedure TJSONImplBaseObj.AfterConstruction;
begin
  inherited;
  dec(FRefCount);//see constructor
end;
 
procedure TJSONImplBaseObj.BeforeDestruction;
begin
  inherited;
  if RefCount<>0 then System.Error(reInvalidPtr);
end;
 
class function TJSONImplBaseObj.NewInstance: TObject;
begin
  Result:=inherited NewInstance;
  //see AfterConstruction, prevent detroy while creating
  TJSONImplBaseObj(Result).FRefCount:=1;
end;
 
function TJSONImplBaseObj.QueryInterface(const IID: TGUID;
  out Obj): HResult;
begin
  if GetInterface(IID,Obj) then Result:=0 else Result:=E_NOINTERFACE;
end;
 
function TJSONImplBaseObj._AddRef: Integer;
begin
  inc(FRefCount);
  Result:=FRefCount;
end;
 
function TJSONImplBaseObj._Release: Integer;
begin
  dec(FRefCount);
  Result:=FRefCount;
  if Result=0 then Destroy;
end;
 
{$ENDIF}
 
{ TJSONDocument }
 
procedure TJSONDocument.AfterConstruction;
begin
  inherited;
  FElementIndex:=0;
  FElementSize:=0;
  FLoadIndex:=0;
  {$IFNDEF JSONDOC_THREADSAFE}
  FGotIndex:=0;
  FGotSorted:=0;
  FGotMatch:=false;
  {$ENDIF}
  FUseIJSONArray:=JSON_UseIJSONArray;
end;
 
destructor TJSONDocument.Destroy;
var
  i:integer;
begin
  for i:=0 to FElementIndex-1 do VarClear(FElements[i].Value);
  inherited;
end;
 
function TJSONDocument.GetKeyIndex(const Key: WideString;
  var GotIndex: integer; var GotSorted: integer): boolean;
var
  a,b,c,d,x:integer;
begin
  //case sensitivity?
  {$IFNDEF JSONDOC_THREADSAFE}
  //check last getindex, speeds up set right after get
  if FGotMatch and (CompareStr(Key,FElements[FGotIndex].Key)=0) then
   begin
    //assert FGotIndex=FSorted[FGotSorted];
    GotIndex:=FGotIndex;
    GotSorted:=FGotSorted;
    Result:=true;
   end
  else
  {$ENDIF}
   begin
    a:=0;
    b:=FElementIndex-1;
    d:=FElementIndex;
    Result:=false;//default
    while b>=a do
     begin
      c:=(a+b) div 2;
      d:=FElements[c].SortIndex;
      //if c=a? c=b?
      x:=CompareStr(Key,FElements[d].Key);
      if x=0 then
       begin
        a:=c;
        b:=c-1;
        Result:=true;
       end
      else
        if x<0 then
          if b=c then dec(b) else b:=c
        else
          if a=c then inc(a) else a:=c;
     end;
    GotSorted:=a;
    GotIndex:=d;
    {$IFNDEF JSONDOC_THREADSAFE}
    FGotSorted:=a;
    FGotIndex:=d;
    FGotMatch:=Result;
    {$ENDIF}
   end;
end;
 
function TJSONDocument.Get_Item(const Key: WideString): Variant;
var
  GotIndex,GotSorted:integer;
begin
  {$IFDEF JSONDOC_THREADSAFE}
  EnterCriticalSection(FLock);
  try
  {$ENDIF}
    if (Self<>nil) and GetKeyIndex(Key,GotIndex,GotSorted)
      and (FElements[GotIndex].LoadIndex=FLoadIndex) then
      Result:=FElements[GotIndex].Value
    else
      Result:=Null;
  {$IFDEF JSONDOC_THREADSAFE}
  finally
    LeaveCriticalSection(FLock);
  end;
  {$ENDIF}
end;
 
function TJSONDocument.ReUse(const Key: WideString): Variant;
var
  GotIndex,GotSorted:integer;
begin
  {$IFDEF JSONDOC_THREADSAFE}
  EnterCriticalSection(FLock);
  try
  {$ENDIF}
    if (Self<>nil) and GetKeyIndex(Key,GotIndex,GotSorted) then
     begin
      FElements[GotIndex].LoadIndex:=FLoadIndex;
      Result:=FElements[GotIndex].Value;
     end
    else
      Result:=Null;
  {$IFDEF JSONDOC_THREADSAFE}
  finally
    LeaveCriticalSection(FLock);
  end;
  {$ENDIF}
end;
 
procedure TJSONDocument.Set_Item(const Key: WideString; const Value: Variant);
var
  i,GotIndex,GotSorted:integer;
const
  GrowStep=$20;//not too much, not too little (?)
begin
  {$IFDEF JSONDOC_THREADSAFE}
  EnterCriticalSection(FLock);
  try
  {$ENDIF}
    //if ((VarType(Value) and varArray)<>0) and (VarArrayDimCount(v)>1) then
    //  raise EJSONException.Create(
    //    'VarArray: multi-dimensional arrays not supported');
    if not GetKeyIndex(Key,GotIndex,GotSorted) then
     begin
      if FElementIndex=FElementSize then
       begin
        inc(FElementSize,GrowStep);
        SetLength(FElements,FElementSize);
       end;
      for i:=FElementIndex-1 downto GotSorted do
        FElements[i+1].SortIndex:=FElements[i].SortIndex;
      GotIndex:=FElementIndex;
      inc(FElementIndex);
      FElements[GotSorted].SortIndex:=GotIndex;
      FElements[GotIndex].Key:=Key;
     end;
    FElements[GotIndex].Value:=Value;
    FElements[GotIndex].LoadIndex:=FLoadIndex;
    //FDirty:=true;
  {$IFDEF JSONDOC_THREADSAFE}
  finally
    LeaveCriticalSection(FLock);
  end;
  {$ENDIF}
end;
 
{$IFDEF JSONDOC_P2}
{$DEFINE JSONDOC_JSON_LOOSE}
{$DEFINE JSONDOC_JSON_PASCAL_STRINGS}
{$ENDIF}
 
procedure TJSONDocument.Parse(const JSONData: WideString);
var
  i,l:integer;
  function SkipWhiteSpace:WideChar;
  begin
    while (i<=l) and (jsonData[i]<=' ') do inc(i);
    if i<=l then Result:=jsonData[i] else Result:=#0;
  end;
  function ExVicinity(di:integer):WideString;
  const
    VicinityExtent=12;
  var
    i:integer;
  begin
    if di<=VicinityExtent then
      Result:=#13#10'(#'+IntToStr(di)+')"'+Copy(jsonData,1,di-1)+
        ' >>> '+jsonData[di]+' <<< '+Copy(jsonData,di+1,VicinityExtent)+'"'
    else
      Result:=#13#10'(#'+IntToStr(di)+')"...'+
        Copy(jsonData,di-VicinityExtent,VicinityExtent)+
        ' >>> '+jsonData[di]+' <<< '+Copy(jsonData,di+1,VicinityExtent)+'"';
    for i:=1 to Length(Result) do
      if word(Result[i])<32 then Result[i]:='|';
  end;
  procedure Expect(c:WideChar;const msg:string);
  begin
    while (i<=l) and (jsonData[i]<=' ') do inc(i);
    if (i<=l) and (jsonData[i]=c) then
      inc(i)
    else
    {$IFDEF JSONDOC_JSON_LOOSE}
      ;
    {$ELSE}
      raise EJSONDecodeException.Create(msg+ExVicinity(i));
    {$ENDIF}
  end;
    procedure GetStringIndexes(var i1,i2:integer);
  begin
    //assert jsonData[i]='"'
    i1:=i;
    inc(i);
    while (i<=l) and (jsonData[i]<>'"') do
     begin
      if jsonData[i]='\' then inc(i);//just skip all to skip any '"'
      inc(i);
     end;
    i2:=i;
    inc(i);
  end;
  {$IFDEF JSONDOC_JSON_PASCAL_STRINGS}
  procedure GetPascalIndexes(var i1,i2:integer);
  begin
    i1:=i;
    while (i<=l) and ((jsonData[i]='''') or (jsonData[i]='#')) do
      if jsonData[i]='''' then
       begin
        inc(i);
        while (i<=l) and (jsonData[i]<>'''') do inc(i);
        if i<=l then inc(i);
       end
      else
       begin
        inc(i);
        if (i<=l) and (jsonData[i]='$') then
         begin
          inc(i);
          while (i<=l) and (word(jsonData[i]) in [$30..$39,$41..$5A,$61..$7A]) do inc(i);
         end
        else
          while (i<=l) and (word(jsonData[i]) in [$30..$39]) do inc(i);
       end;
    i2:=i;
  end;
  {$ENDIF}
  function GetStringValue(i1,i2:integer):WideString;
  var
    ii,di,u,v,w:integer;
  begin
    //assert i1<=l
    //assert i2<=l
    //assert i1<i2
    {$IFDEF JSONDOC_JSON_PASCAL_STRINGS}
    if (jsonData[i1]='''') or (jsonData[i1]='#') then
     begin
      SetLength(Result,i2-i1);
      ii:=1;
      di:=i1;
      while di<i2 do
       begin
        case AnsiChar(jsonData[di]) of
          '''':
           begin
            inc(di);
            u:=0;
            while (di<i2) and (u=0) do
             begin
              if jsonData[di]='''' then
               begin
                inc(di);
                if (di<=l) and (jsonData[di]='''') then
                 begin
                  Result[ii]:='''';
                  inc(ii);
                  inc(di);
                 end
                else
                  u:=1;
               end
              else
               begin
                Result[ii]:=jsonData[di];
                inc(ii);
                inc(di);
               end;
             end;
           end;
          '#':
           begin
            inc(di);
            if (di<i2) and (jsonData[di]='$') then
             begin
              w:=0;
              u:=0;
              inc(di);
              while (u<4) and (di<i2) and (word(jsonData[di]) in [$30..$39,$41..$5A,$61..$7A]) do
               begin
                if di=i2 then raise EJSONDecodeException.Create(
                  'JSON Incomplete espace sequence'+ExVicinity(di));
                v:=word(jsonData[di]);
                case v of
                  $30..$39:w:=(w shl 4) or (v and $F);
                  $41..$5A,$61..$7A:w:=(w shl 4) or ((v and $1F)+9);
                  else raise EJSONDecodeException.Create(
                    'JSON Invalid espace sequence'+ExVicinity(di));
                end;
                inc(di);
                inc(u);
               end;
              Result[ii]:=WideChar(w);
              inc(ii);
             end
            else
             begin
              w:=0;
              u:=0;
              while (u<5) and (di<i2) and (word(jsonData[di]) in [$30..$39]) do
               begin
                if di=i2 then raise EJSONDecodeException.Create(
                  'JSON Incomplete espace sequence'+ExVicinity(di));
                w:=w*10+(word(jsonData[di]) and $F);
                inc(di);
                inc(u);
               end;
              Result[ii]:=WideChar(w);
              inc(ii);
             end;
           end;
          else raise EJSONDecodeException.Create(
            'JSON Unknown pascal string syntax'+ExVicinity(di));
        end;
       end;
      SetLength(Result,ii-1);
     end
    else
    {$ENDIF}
     begin
      {$IFDEF JSONDOC_JSON_STRICT}
      //assert jsonData[i1]='"'
      //assert jsonData[i2]='"';
      inc(i1);
      {$ELSE}
      if jsonData[i1]='"' then inc(i1);
      {$ENDIF}
      SetLength(Result,i2-i1);
      ii:=1;
      di:=i1;
      while di<i2 do
       begin
        //assert ii<=Length(Result);
        if jsonData[di]='\' then
         begin
          inc(di);
          case AnsiChar(jsonData[di]) of
            '"','\','/':Result[ii]:=jsonData[di];
            'b':Result[ii]:=#8;
            't':Result[ii]:=#9;
            'n':Result[ii]:=#10;
            'f':Result[ii]:=#12;
            'r':Result[ii]:=#13;
            'x':
             begin
              inc(di);
              if di=i2 then raise EJSONDecodeException.Create(
                'JSON Incomplete espace sequence'+ExVicinity(di));
              v:=word(jsonData[di]);
              case v of
                $30..$39:w:=(v and $F) shl 4;
                $41..$5A,$61..$7A:w:=((v and $1F)+9) shl 4;
                else raise EJSONDecodeException.Create(
                  'JSON Invalid espace sequence'+ExVicinity(di));
              end;
              inc(di);
              if di=i2 then raise EJSONDecodeException.Create(
                'JSON Incomplete espace sequence'+ExVicinity(di));
              v:=word(jsonData[di]);
              case v of
                $30..$39:w:=w or (v and $F);
                $41..$5A,$61..$7A:w:=w or ((v and $1F)+9);
                else raise EJSONDecodeException.Create(
                  'JSON Invalid espace sequence'+ExVicinity(di));
              end;
              Result[ii]:=WideChar(w);
             end;
            'u':
             begin
              w:=0;
              for u:=0 to 3 do
               begin
                inc(di);
                if di=i2 then raise EJSONDecodeException.Create(
                  'JSON Incomplete espace sequence'+ExVicinity(di));
                v:=word(jsonData[di]);
                case v of
                  $30..$39:w:=(w shl 4) or (v and $F);
                  $41..$5A,$61..$7A:w:=(w shl 4) or ((v and $1F)+9);
                  else raise EJSONDecodeException.Create(
                    'JSON Invalid espace sequence'+ExVicinity(di));
                end;
               end;
              Result[ii]:=WideChar(w);
             end;
            else raise EJSONDecodeException.Create(
              'JSON Unknown escape sequence'+ExVicinity(di));
          end;
         end
        else
          Result[ii]:=jsonData[di];
        inc(di);
        inc(ii);
       end;
      SetLength(Result,ii-1);
     end;
  end;
const
  stackGrowStep=$20;//not too much, not too little (?)
  arrGrowStep=$20;
var
  IsArray:boolean;
  k1,k2,v1,v2,a1,ai,al:integer;
  d:IJSONDocument;
  a:array of Variant;
  at,vt:TVarType;
  procedure SetValue(const v:Variant);
  begin
    //assert da=nil
    if IsArray then
     begin
      if ai=al then
       begin
        inc(al,arrGrowStep);//not too much, not too little (?)
        SetLength(a,al);
       end;
      a[ai]:=v;
      //detect same type elements array
      vt:=TVarData(v).VType;
      case at of
        varEmpty:
          at:=vt;
        varShortInt,varByte://i1,u1
          case vt of
            varSmallInt,varInteger,varSingle,varDouble,
            varLongWord,varInt64,$0015:
              at:=vt;
            varShortInt:
              ;//at:=varShortInt;
            else
              at:=varVariant;
          end;
        varSmallint,varWord://i2,u2
          case vt of
            varInteger,varSingle,varDouble,varLongWord,varInt64,$0015:
              at:=vt;
            varSmallInt,
            varShortInt,varByte,varWord:
              ;//at:=varSmallInt;
            else
              at:=varVariant;
          end;
        varInteger,varLongWord://i4,u4
          case vt of
            varSingle,varDouble,varInt64,$0015:
              at:=vt;
            varSmallInt,varInteger,
            varShortInt,varByte,varWord,varLongWord:
              ;//at:=varInteger;
            else
              at:=varVariant;
          end;
        varInt64,$0015://i8
          case vt of
            varSingle,varDouble:
              at:=vt;
            varSmallInt,varInteger,
            varShortInt,varByte,varWord,varLongWord,varInt64,$0015:
              ;//at:=varInt64;
            else
              at:=varVariant;
          end;
        varSingle:
          case vt of
            varDouble:
              at:=vt;
            varSmallInt,varInteger,varSingle,
            varShortInt,varByte,varWord,varLongWord:
              ;//at:=varSingle
            else
              at:=varVariant;
          end;
        varDouble:
          case vt of
            varSmallInt,varInteger,varSingle,varDouble,
            varShortInt,varByte,varWord,varLongWord:
              ;//at:=varDouble
            else
              at:=varVariant;
          end;
        varVariant:
          ;//Already creating an VarArray of varVariant
        else
          if at<>vt then at:=varVariant;
      end;
      inc(ai);
     end
    else
      d[GetStringValue(k1,k2)]:=v
  end;
var
  firstItem,b:boolean;
  stack:array of record
    k1,k2:integer;
    d:IJSONDocument;
  end;
  stackIndex,stackSize:integer;
  ods:char;
  key:WideString;
  d1:IJSONDocument;
  dr:IJSONDocWithReUse;
  da:IJSONDocArray;
  aa:TJSONArray;
  da0,da1:integer;
  v:Variant;
  v64:int64;
  procedure CheckValue;
  begin
    //assert da<>nil
    if stackIndex=da0 then
      raise EJSONDecodeException.Create('IJSONDocArray: non-document element in array');
  end;
begin
  {$IFDEF JSONDOC_THREADSAFE}
  EnterCriticalSection(FLock);
  try
  {$ENDIF}
    //Clear;? let caller decide.
    i:=1;
    l:=Length(jsonData);
    //object starts
    Expect('{','JSON doesn''t define an object, "{" expected.');
    stackSize:=0;
    stackIndex:=0;
    ai:=0;
    a1:=0;
    al:=0;
    da:=nil;
    da0:=0;
    da1:=0;
    IsArray:=false;
    firstItem:=true;
 
    {$if CompilerVersion >= 24}
    ods:=FormatSettings.DecimalSeparator;
    {$else}
    ods:=DecimalSeparator;
    {$ifend}
 
    try
 
      {$if CompilerVersion >= 24}
      FormatSettings.DecimalSeparator:='.';
      {$else}
      DecimalSeparator:='.';
      {$ifend}
 
      d:=Self;
      //main loop over key/values and nested objects/arrays
      while (i<=l) and (stackIndex<>-1) do
       begin
        if firstItem then firstItem:=false else
          Expect(',','JSON element not delimited by comma');
        if not(IsArray) and (SkipWhiteSpace<>'}') then
         begin
          //key string
          case AnsiChar(SkipWhiteSpace) of
            '"':
              GetStringIndexes(k1,k2);
            {$IFDEF JSONDOC_JSON_PASCAL_STRINGS}
            '''','#':
              GetPascalIndexes(k1,k2);
            {$ENDIF}
            else
            {$IFDEF JSONDOC_JSON_STRICT}
              raise EJSONDecodeException.Create(
                'JSON key string not enclosed in double quotes'+ExVicinity(i));
            {$ELSE}
             begin
              k1:=i;
              while (i<=l) and (jsonData[i]>' ') and not(
                (jsonData[i]=':') or (jsonData[i]='"')
                {$IFDEF JSONDOC_JSON_LOOSE}
                or (jsonData[i]='{') or (jsonData[i]='[')
                or (jsonData[i]='=') or (jsonData[i]=';')
                {$ENDIF}
                ) do inc(i);
              k2:=i;
             end;
            {$ENDIF}
          end;
          Expect(':','JSON key, value not separated by colon');
          {$IFDEF JSONDOC_JSON_LOOSE}
          if (i<=l) and (jsonData[i]='=') then inc(i);
          {$ENDIF}
         end;
        //value
        case AnsiChar(SkipWhiteSpace) of
          '{','['://object or array
           begin
            b:=IsArray;
            if jsonData[i]='{' then
             begin
              //an object starts
              if da=nil then
                if IsArray then
                 begin
                  if ai=al then
                   begin
                    inc(al,arrGrowStep);//not too much, not too little (?)
                    SetLength(a,al);
                   end;
                  v:=JSON;
                  a[ai]:=v;
                  //detect same type elements array
                  if at=varEmpty then at:=varUnknown else
                    if at<>varUnknown then at:=varVariant;
                  inc(ai);
                 end
                else
                 begin
                  key:=GetStringValue(k1,k2);
                  if d.QueryInterface(IID_IJSONDocWithReUse,dr)=S_OK then
                   begin
                    v:=dr.ReUse(key);
                    dr:=nil;
                   end
                  else
                    v:=Null;
                  if (TVarData(v).VType in [varDispatch,varUnknown]) and
                    (TVarData(v).VUnknown<>nil) and
                    (IUnknown(v).QueryInterface(IID_IJSONDocument,d1)=S_OK) then
                    d1:=nil
                  else
                   begin
                    v:=JSON;
                    d[key]:=v;
                   end;
                 end
              else
                if da0=stackIndex then da1:=i;
              IsArray:=false;
             end
            else
             begin
              //an array starts
              if da=nil then
                if d.QueryInterface(IID_IJSONDocWithReUse,dr)=S_OK then
                 begin
                  key:=GetStringValue(k1,k2);
                  v:=dr.ReUse(key);
                  dr:=nil;
                  if (TVarData(v).VType in [varDispatch,varUnknown]) and
                    (TVarData(v).VUnknown<>nil) and
                    (IUnknown(v).QueryInterface(IID_IJSONDocArray,da)=S_OK) then
                   begin
                    da0:=stackIndex+1;
                    da1:=0;//see first '{' above
                   end;
                 end;
              IsArray:=true;
             end;
            inc(i);
            //push onto stack
            if stackIndex=stackSize then
             begin
              inc(stackSize,stackGrowStep);
              SetLength(stack,stackSize);
             end;
            if b then //if WasArray then
             begin
              stack[stackIndex].k1:=a1;
              stack[stackIndex].k2:=at;
              stack[stackIndex].d:=nil;
             end
            else
             begin
              stack[stackIndex].k1:=k1;
              stack[stackIndex].k2:=k2;
              stack[stackIndex].d:=d;
             end;
            inc(stackIndex);
            firstItem:=true;
            if da=nil then
              if IsArray then
               begin
                a1:=ai;
                at:=varEmpty;//used to detect same type elements array
               end
              else
                d:=IUnknown(v) as IJSONDocument;
           end;
 
          '}',']':;//empty object or array, drop into close array below
 
          '"'://string
           begin
            GetStringIndexes(v1,v2);
            if da=nil then
              SetValue(GetStringValue(v1,v2))
            else
              CheckValue;
           end;
 
          {$IFDEF JSONDOC_JSON_PASCAL_STRINGS}
          '''','#'://pascal-style string
           begin
            GetPascalIndexes(v1,v2);
            if da=nil then
              SetValue(GetStringValue(v1,v2))
            else
              CheckValue;
           end;
          '$'://pascal-style hex digit
           begin
            inc(i);
            v1:=i;
            v64:=0;
            while (i<=l) and (word(jsonData[i]) in [$30..$39,$41..$5A,$61..$7A]) do
             begin
              case word(jsonData[i]) of
                $30..$39:v64:=(v64 shl 4) or (word(jsonData[i]) and $F);
                $41..$5A,$61..$7A:v64:=(v64 shl 4) or ((word(jsonData[i]) and $1F)+9);
                else raise EJSONDecodeException.Create(
                  'JSON Invalid espace sequence'+ExVicinity(i));
              end;
              inc(i);
             end;
            if i=v1 then
              raise EJSONDecodeException.Create(
                'JSON Unrecognized value type'+ExVicinity(i));
            if v64>=$80000000 then //int64
              SetValue(v64)
            else if v64>=$80 then //int32
              SetValue(integer(v64))
            else //int8
              SetValue(SmallInt(v64));
           end;
          {$ENDIF}
 
          '0'..'9','-'://number
           begin
            b:=jsonData[i]='-';
            v1:=i;
            if b then inc(i);
            if da=nil then
             begin
              v64:=0;
              while (i<=l) and (word(jsonData[i]) in [$30..$39]) do
               begin
                v64:=v64*10+(word(jsonData[i]) and $F);//TODO: detect overflow
                inc(i);
               end;
              if AnsiChar(jsonData[i]) in ['.','e','E'] then
               begin
                //float
                inc(i);
                while (i<=l) and (AnsiChar(jsonData[i]) in
                  ['0'..'9','-','+','e','E']) do inc(i);
                //try except EConvertError?
                SetValue(StrToFloat(Copy(jsonData,v1,i-v1)));
               end
              else
               begin
                //integer
                if v64>=$80000000 then //int64
                  if b then SetValue(-v64) else SetValue(v64)
                else if v64>=$80 then //int32
                  if b then SetValue(-integer(v64)) else SetValue(integer(v64))
                else //int8
                  if b then SetValue(-SmallInt(v64)) else SetValue(SmallInt(v64));
               end;
             end
            else
             begin
              //skip
              CheckValue;
              while (i<=l) and (word(jsonData[i]) in [$30..$39]) do inc(i);
              if AnsiChar(jsonData[i]) in ['.','e','E'] then
               begin
                inc(i);
                while (i<=l) and (AnsiChar(jsonData[i]) in
                  ['0'..'9','-','+','e','E']) do inc(i);
               end;
             end;
           end;
 
          {$IFDEF JSONDOC_JSON_LOOSE}
          ';':inc(i);
          else
           begin
            v1:=i;
            while (i<=l) and (jsonData[i]>' ') and not(
              (jsonData[i]=':') or (jsonData[i]=',') or (jsonData[i]='"')
              or (jsonData[i]='}') or (jsonData[i]=']')
              {$IFDEF JSONDOC_JSON_PASCAL_STRINGS}
              or (jsonData[i]='''')
              {$ENDIF}
              ) do inc(i);
            v2:=i;
            if v1=v2 then
              raise EJSONDecodeException.Create(
                'JSON Value expected'+ExVicinity(i));
            if da=nil then
              if (v2-v1=4) and (jsonData[v1]='t') and (jsonData[v1+1]='r') and
                (jsonData[v1+2]='u') and (jsonData[v1+3]='e') then
                SetValue(true)
              else
              if (v2-v1=5) and (jsonData[v1]='f') and (jsonData[v1+1]='a') and
                (jsonData[v1+2]='l') and (jsonData[v1+3]='s') and (jsonData[v1+4]='e') then
                SetValue(false)
              else
              if (v2-v1=4) and (jsonData[v1]='n') and (jsonData[v1+1]='u') and
                (jsonData[v1+2]='l') and (jsonData[v1+3]='l') then
                SetValue(Null)
              else
                SetValue(GetStringValue(v1,v2))
            else
              CheckValue;
           end;
          {$ELSE}
 
          't'://true
           begin
            inc(i);
            Expect('r','JSON true misspelled');
            Expect('u','JSON true misspelled');
            Expect('e','JSON true misspelled');
            if da=nil then SetValue(true) else CheckValue;
           end;
          'f'://false
           begin
            inc(i);
            Expect('a','JSON false misspelled');
            Expect('l','JSON false misspelled');
            Expect('s','JSON false misspelled');
            Expect('e','JSON false misspelled');
            if da=nil then SetValue(false) else CheckValue;
           end;
          'n'://null
           begin
            inc(i);
            Expect('u','JSON null misspelled');
            Expect('l','JSON null misspelled');
            Expect('l','JSON null misspelled');
            if da=nil then SetValue(Null) else CheckValue;
            //TODO: support null in IJSONDocArray
           end;
 
          else
            raise EJSONDecodeException.Create(
              'JSON Unrecognized value type'+ExVicinity(i));
          {$ENDIF}
        end;
        if not firstItem then
         begin
          b:=true;
          while b do
           begin
            v:=Null;
            if IsArray then
              if SkipWhiteSpace=']' then
               begin
                if da=nil then
                 begin
                  if FUseIJSONArray then
                   begin
                    aa:=TJSONArray.Create(ai-a1);
                    k1:=a1;
                    k2:=0;
                    while k1<ai do
                     begin
                      //aa[k2]:=a[k1];VarClear(a[k1]);
                      VarMove(aa.FData[k2],a[k1]);
                      inc(k1);
                      inc(k2);
                     end;
                    v:=aa as IJSONArray;
                   end
                  else
                   begin
                    if not(VarTypeIsValidArrayType(at)) then at:=varVariant;
                    v:=VarArrayCreate([0,ai-a1-1],at);
                    k1:=a1;
                    k2:=0;
                    while k1<ai do
                     begin
                      v[k2]:=a[k1];
                      VarClear(a[k1]);
                      inc(k1);
                      inc(k2);
                     end;
                   end;
                  ai:=a1;
                 end;
               end
              else
                b:=false
            else
              b:=SkipWhiteSpace='}';
            if b then
             begin
              inc(i);
              //pop from stack
              if stackIndex=0 then
               begin
                //EndIndex:=i;
                dec(stackIndex);//stackindex:=-1;
                b:=false;
               end
              else
               begin
                dec(stackIndex);
                if stack[stackIndex].d=nil then
                 begin
                  a1:=stack[stackIndex].k1;
                  at:=stack[stackIndex].k2;
                  IsArray:=true;
                 end
                else
                 begin
                  if da=nil then d:=stack[stackIndex].d;
                  k1:=stack[stackIndex].k1;
                  k2:=stack[stackIndex].k2;
                  stack[stackIndex].d:=nil;
                  IsArray:=false;
                 end;
                if da<>nil then
                  if stackIndex=da0 then
                    da.AddJSON(Copy(jsonData,da1,i-da1))
                  else
                    if stackIndex=da0-1 then
                      da:=nil;//done
               end;
              //set array
              if (da=nil) and (TVarData(v).VType<>varNull) then SetValue(v);
             end;
           end;
         end;
       end;
      {$IFNDEF JSONDOC_JSON_LOOSE}
      if stackIndex<>-1 then raise EJSONDecodeException.Create(
        'JSON with '+IntToStr(stackIndex+1)+' objects or arrays not closed');
      {$ENDIF}
      if (i<=l) and (SkipWhiteSpace<>#0) then raise EJSONDecodeException.Create(
        'JSON has unexpected data after root document '+ExVicinity(i));
    finally
      {$if CompilerVersion >= 24}
      FormatSettings.DecimalSeparator:=ods;
      {$else}
      DecimalSeparator:=ods;
      {$ifend}
    end;
  {$IFDEF JSONDOC_THREADSAFE}
  finally
    LeaveCriticalSection(FLock);
  end;
  {$ENDIF}
end;
 
function JSONEncodeStr(const xx:WideString):WideString;
const
  resGrowStep=$100;
  hex:array[0..15] of WideChar=(
    '0','1','2','3','4','5','6','7',
    '8','9','A','B','C','D','E','F');
var
  i,j,k,l:integer;
  w:word;
begin
  l:=Length(xx);
  SetLength(Result,l+2);
  Result[1]:='"';
  i:=1;
  j:=1;
  k:=l+2;
  while i<=l do
   begin
    w:=word(xx[i]);
    case w of
      0..31,word('"'),word('\'):
       begin
        if j+3>k then
         begin
          k:=((k div resGrowStep)+1)*resGrowStep;
          SetLength(Result,k);
         end;
        inc(j);
        Result[j]:='\';
        inc(j);
        case w of
          8:Result[j]:='b';
          9:Result[j]:='t';
          10:Result[j]:='n';
          12:Result[j]:='f';
          13:Result[j]:='r';
          word('"'),word('\'):Result[j]:=xx[i];
          else
           begin
            Result[j]:='u';
            if j+4>k then
             begin
              k:=((k div resGrowStep)+1)*resGrowStep;
              SetLength(Result,k);
             end;
            inc(j);Result[j]:=hex[w shr 12];
            inc(j);Result[j]:=hex[w shr 8 and $F];
            inc(j);Result[j]:=hex[w shr 4 and $F];
            inc(j);Result[j]:=hex[w and $F];
           end;
        end;
       end;
      else
       begin
        if j+2>k then
         begin
          k:=((k div resGrowStep)+1)*resGrowStep;
          SetLength(Result,k);
         end;
        inc(j);
        Result[j]:=WideChar(w);
       end;
    end;
    inc(i);
   end;
  inc(j);
  Result[j]:='"';
  SetLength(Result,j);
end;
 
{
function JSONVarToStr(const v: Variant):WideString;
begin
  if (TVarData(v).VType and varArray)=0 then
    Result:=JSONVarToStr1(v)
  else
    .....
end;
}
 
function JSONVarToStr1(const v: Variant):WideString;
var
  uu:IUnknown;
  d:IJSONDocument;
  da:IJSONArray;
begin
  case TVarData(v).VType and varTypeMask of
    varNull:Result:='null';
    varSmallint,varInteger,varShortInt,
    varByte,varWord,varLongWord,varInt64:
      Result:=VarToWideStr(v);
    varSingle,varDouble,varCurrency:
      Result:=FloatToStr(v);//?
    varDate:
      //Result:=FloatToStr(VarToDateTime(v));//?
      Result:='"'+FormatDateTime('yyyy-mm-dd"T"hh:nn:ss.zzz',
        VarToDateTime(v))+'"';
    varOleStr,varString,$0102:
      Result:=JSONEncodeStr(VarToWideStr(v));
    varBoolean:
      if v then Result:='true' else Result:='false';
    varDispatch,varUnknown:
     begin
      uu:=IUnknown(v);
      if uu=nil then Result:='null'
      else
      if uu.QueryInterface(IID_IJSONDocument,d)=S_OK then
       begin
        //revert to ToString
        Result:=d.ToString;
        d:=nil;
       end
      else
      if uu.QueryInterface(IID_IJSONArray,da)=S_OK then
       begin
        //TODO: re-do indenting
        Result:=da.ToString;
        da:=nil;
       end
      else
      //IRegExp2? IStream? IPersistStream?
        raise EJSONEncodeException.Create(
          'No supported interface found on object');
     end;
    else raise EJSONEncodeException.Create(
      'Unsupported variant type '+IntToHex(TVarData(v).VType,4));
  end;
end;
 
function TJSONDocument.JSONToString: WideString;
const
  stackGrowStep=$20;
var
  e:IJSONEnumerator;
  IsArray,firstItem:boolean;
  stack:array of record
    e:IJSONEnumerator;
    IsArray:boolean;
  end;
  stackLength,stackIndex:integer;
  function ExTrace:string;
  var
    i:integer;
  begin
    if IsArray then
      Result:=' #'+e.Key
    else
      Result:=' "'+e.Key+'"';
    i:=stackIndex;
    while i<>0 do
     begin
      dec(i);
      if stack[i].IsArray then
        Result:=' #'+stack[i].e.Key+Result
      else
        Result:=' "'+stack[i].e.Key+'"'+Result;
     end;
  end;
const
  resultGrowStep=$4000;
var
  wi,wl:cardinal;
{$IFDEF JSONDOC_STOREINDENTING}
const
  tabs=#13#10#9#9#9#9#9#9#9#9#9#9#9#9#9#9;
var
  tabIndex:integer;
  procedure wr(const xx,yy,zz:WideString);
  var
    xi,xj,xk,xl,yi,yl,zl:cardinal;
  begin
    xi:=1;
    xl:=Length(xx);
    yl:=Length(yy);//assert <>0
    zl:=Length(zz);
    while xi<=xl do
     begin
      xj:=xi;
      yi:=0;
      while (xi<=xl) and (yi<yl) do
       begin
        if (xx[xi]=yy[1]) and (xi+yl<=xl) then
         begin
          while (yi<yl) and (xx[xi+yi]=yy[1+yi]) do inc(yi);
          if yi<yl then inc(xi);
         end
        else
          inc(xi);
       end;
      xk:=xi-xj;
      while wi+xk>wl do
       begin
        //grow
        inc(wl,resultGrowStep);
        SetLength(Result,wl);
       end;
      Move(xx[xj],Result[wi+1],xk*2);
      inc(wi,xk);
      if xi<=xl then
       begin
        inc(xi,yl);
        while wi+zl>wl do
         begin
          //grow
          inc(wl,resultGrowStep);
          SetLength(Result,wl);
         end;
        Move(zz[1],Result[wi+1],zl*2);
        inc(wi,zl);
       end;
     end;
  end;
{$ENDIF}
  procedure w(const xx:WideString);
  var
    xl:cardinal;
  begin
    xl:=Length(xx);
    while wi+xl>wl do
     begin
      //grow
      inc(wl,resultGrowStep);
      SetLength(Result,wl);
     end;
    Move(xx[1],Result[wi+1],xl*2);
    inc(wi,xl);
  end;
  procedure Push(const NewEnum:IJSONEnumerator;NewIsArray:boolean);
  begin
    if stackIndex=stackLength then
     begin
      inc(stackLength,stackGrowStep);
      SetLength(stack,stackLength);
     end;
    stack[stackIndex].e:=e;
    stack[stackIndex].IsArray:=IsArray;
    inc(stackIndex);
    e:=NewEnum;
    IsArray:=NewIsArray;
    if IsArray then w('[') else w('{');
    firstItem:=true;
    {$IFDEF JSONDOC_STOREINDENTING}
    inc(tabIndex);
    {$ENDIF}
  end;
var
  ods:char;
  vt:TVarType;
  uu:IUnknown;
  d:IJSONDocument;
  de:IJSONEnumerable;
  da1:IJSONArray;
  da:IJSONDocArray;
begin
  if Self=nil then
   begin
    Result:='null';
    Exit;
   end;
  {$IFDEF JSONDOC_THREADSAFE}
  EnterCriticalSection(FLock);
  try
  {$ENDIF}
    wi:=1;
    wl:=resultGrowStep;
    SetLength(Result,wl);
    Result[1]:='{';
 
    stackLength:=0;
    stackIndex:=0;
    e:=TJSONEnumerator.Create(Self);
    IsArray:=false;
 
    {$if CompilerVersion >= 24}
    ods:= FormatSettings.DecimalSeparator;
    {$else}
    ods:=DecimalSeparator;
    {$ifend}
    try
      {$if CompilerVersion >= 24}
      FormatSettings.DecimalSeparator:='.';
      {$else}
      DecimalSeparator:='.';
      {$ifend}
 
      //w('{');//see above
      firstItem:=true;
      {$IFDEF JSONDOC_STOREINDENTING}
      tabIndex:=3;
      {$ENDIF}
      while e<>nil do
        if e.Next then
         begin
          if firstItem then firstItem:=false else w(',');
          {$IFDEF JSONDOC_STOREINDENTING}
          w(Copy(tabs,1,tabIndex));
          {$ENDIF}
          if not IsArray then
           begin
            w(JSONEncodeStr(e.Key));
            {$IFDEF JSONDOC_STOREINDENTING}
            w(': ');
            {$ELSE}
            w(':');
            {$ENDIF}
           end;
          //write value
          vt:=TVarData(PVariant(e.v0)^).VType;
          //if (vt and varByRef)<>0 then
          //  raise EJSONEncodeException.Create('VarByRef: not implemented'+ExTrace);
          if (vt and varArray)=0 then
           begin
            //not an array, plain value
            //TODO: deduplicate with JSONVarToStr1(PVariant(e.v0)^);
            case vt and varTypeMask of
              varNull:w('null');
              varSmallint,varInteger,varShortInt,
              varByte,varWord,varLongWord,varInt64:
                w(VarToWideStr(PVariant(e.v0)^));
              varSingle,varDouble,varCurrency:
                w(FloatToStr(PVariant(e.v0)^));//?
              varDate:
               begin
                //w(FloatToStr(VarToDateTime(v)));//?
                w('"');
                //TODO:"yyyy-mm-dd hh:nn:ss.zzz"? $date?
                w(FormatDateTime('yyyy-mm-dd"T"hh:nn:ss.zzz',VarToDateTime(PVariant(e.v0)^)));
                w('"');
               end;
              varOleStr,varString,$0102:
                w(JSONEncodeStr(VarToWideStr(PVariant(e.v0)^)));
              varBoolean:
                if PVariant(e.v0)^ then w('true') else w('false');
              varDispatch,varUnknown:
               begin
                uu:=IUnknown(PVariant(e.v0)^);
                if uu=nil then w('null')
                else
                if uu.QueryInterface(IID_IJSONEnumerable,de)=S_OK then
                 begin
                  Push(de.NewEnumerator,false);
                  de:=nil;
                 end
                else
                if uu.QueryInterface(IID_IJSONDocument,d)=S_OK then
                 begin
                  //revert to ToString
                  w(d.ToString);
                  d:=nil;
                 end
                else
                if uu.QueryInterface(IID_IJSONDocArray,da)=S_OK then
                 begin
                  {$IFDEF JSONDOC_STOREINDENTING}
                  wr(da.ToString,#13#10,Copy(tabs,1,tabIndex));
                  {$ELSE}
                  w(da.ToString);
                  {$ENDIF}
                  da:=nil;
                 end
                else
                if uu.QueryInterface(IID_IJSONArray,da1)=S_OK then
                 begin
                  Push(TJSONArrayEnumerator.Create(da1),true);
                  da1:=nil;
                 end
                else
                //IRegExp2? IStream? IPersistStream?
                  raise EJSONEncodeException.Create(
                    'No supported interface found on object'+ExTrace);
               end;
              else raise EJSONEncodeException.Create(
                'Unsupported variant type '+IntToHex(vt,4)+ExTrace);
            end;
           end
          else
           begin
            //TODO: if (vt and varTypeMask)=varByte then BLOB?
            Push(TVarArrayEnumerator.Create(e.v0),true);
           end;
         end
        else
         begin
          {$IFDEF JSONDOC_STOREINDENTING}
          dec(tabIndex);
          if not firstItem then w(Copy(tabs,1,tabIndex));
          {$ENDIF}
          if IsArray then w(']') else w('}');
          firstItem:=false;
          if stackIndex=0 then
            e:=nil
          else
           begin
            //pop from stack
            dec(stackIndex);
            e:=stack[stackIndex].e;
            IsArray:=stack[stackIndex].IsArray;
            stack[stackIndex].e:=nil;
           end;
         end;
 
      SetLength(Result,wi);
 
    finally
      {$if CompilerVersion >= 24}
      FormatSettings.DecimalSeparator:=ods;
      {$else}
      DecimalSeparator:=ods;
      {$ifend}
    end;
  {$IFDEF JSONDOC_THREADSAFE}
  finally
    LeaveCriticalSection(FLock);
  end;
  {$ENDIF}
end;
 
function TJSONDocument.ToVarArray: Variant;
var
  i,l:integer;
begin
  if Self=nil then
   begin
    Result:=Null;
    Exit;
   end;
  {$IFDEF JSONDOC_THREADSAFE}
  EnterCriticalSection(FLock);
  try
  {$ENDIF}
    l:=0;
    for i:=0 to FElementIndex-1 do
      if FElements[i].LoadIndex=FLoadIndex then inc(l);
        //and not(VarIsNull(FElements[i].Value))?
    Result:=VarArrayCreate([0,l-1,0,1],varVariant);
    l:=0;
    for i:=0 to FElementIndex-1 do
      if FElements[i].LoadIndex=FLoadIndex then
       begin
        Result[l,0]:=FElements[i].Key;
        Result[l,1]:=FElements[i].Value;
        inc(l);
       end;
  {$IFDEF JSONDOC_THREADSAFE}
  finally
    LeaveCriticalSection(FLock);
  end;
  {$ENDIF}
end;
 
procedure TJSONDocument.Clear;
var
  i:integer;
  uu:IUnknown;
  d:IJSONDocument;
  da:IJSONDocArray;
begin
  {$IFDEF JSONDOC_THREADSAFE}
  EnterCriticalSection(FLock);
  try
  {$ELSE}
    FGotMatch:=false;
  {$ENDIF}
    //FDirty:=false;
    for i:=0 to FElementIndex-1 do
      if TVarData(FElements[i].Value).VType=varUnknown then
       begin
        uu:=IUnknown(FElements[i].Value);
        if uu=nil then
          VarClear(FElements[i].Value)
        else
        if uu.QueryInterface(IID_IJSONDocument,d)=S_OK then
         begin
          d.Clear;
          d:=nil;
         end
        else
        if uu.QueryInterface(IID_IJSONDocArray,da)=S_OK then
         begin
          da.Clear;
          da:=nil;
         end
        else
          VarClear(FElements[i].Value);
       end
      else
        VarClear(FElements[i].Value);
    inc(FLoadIndex);
  {$IFDEF JSONDOC_THREADSAFE}
  finally
    LeaveCriticalSection(FLock);
  end;
  {$ENDIF}
end;
 
procedure TJSONDocument.Delete(const Key: WideString);
var
  GotIndex,GotSorted:integer;
  uu:IUnknown;
  d:IJSONDocument;
  da:IJSONDocArray;
begin
  {$IFDEF JSONDOC_THREADSAFE}
  EnterCriticalSection(FLock);
  try
  {$ENDIF}
    if GetKeyIndex(Key,GotIndex,GotSorted) then
     begin
      if TVarData(FElements[GotIndex].Value).VType=varUnknown then
       begin
        uu:=IUnknown(FElements[GotIndex].Value);
        if uu=nil then
          VarClear(FElements[GotIndex].Value)
        else
        if uu.QueryInterface(IID_IJSONDocument,d)=S_OK then
         begin
          d.Clear;
          d:=nil;
         end
        else
        if uu.QueryInterface(IID_IJSONDocArray,da)=S_OK then
         begin
          da.Clear;
          da:=nil;
         end
        else
          VarClear(FElements[GotIndex].Value);
       end
      else
        VarClear(FElements[GotIndex].Value);
      FElements[GotIndex].LoadIndex:=FLoadIndex-1;
     end;
    //else raise?
    //FDirty:=true;
  {$IFDEF JSONDOC_THREADSAFE}
  finally
    LeaveCriticalSection(FLock);
  end;
  {$ENDIF}
end;
 
function TJSONDocument.NewEnumerator: IJSONEnumerator;
begin
  Result:=TJSONEnumerator.Create(Self);
end;
 
{ TJSONEnumerator }
 
constructor TJSONEnumerator.Create(Data: TJSONDocument);
begin
  inherited Create;
  FData:=Data;
  FIndex:=-1;
  //TODO: hook into TJSONDocument destructor?
end;
 
destructor TJSONEnumerator.Destroy;
begin
  FData:=nil;
  inherited;
end;
 
function TJSONEnumerator.EOF: boolean;
var
  i:integer;
begin
  if FData=nil then
    Result:=true
  else
   begin
    {$IFDEF JSONDOC_THREADSAFE}
    EnterCriticalSection(FData.FLock);
    try
    {$ENDIF}
      i:=FIndex;
      if i=-1 then i:=0;
      while (i<FData.FElementIndex) and
        (FData.FElements[i].LoadIndex<>FData.FLoadIndex) do
        inc(i);
      Result:=i>=FData.FElementIndex;
    {$IFDEF JSONDOC_THREADSAFE}
    finally
      LeaveCriticalSection(FData.FLock);
    end;
    {$ENDIF}
   end;
end;
 
function TJSONEnumerator.Next: boolean;
begin
  if FData=nil then
    Result:=false
  else
   begin
    {$IFDEF JSONDOC_THREADSAFE}
    EnterCriticalSection(FData.FLock);
    try
    {$ENDIF}
      inc(FIndex);
      while (FIndex<FData.FElementIndex) and
        (FData.FElements[FIndex].LoadIndex<>FData.FLoadIndex) do
        inc(FIndex);
      Result:=FIndex<FData.FElementIndex;
    {$IFDEF JSONDOC_THREADSAFE}
    finally
      LeaveCriticalSection(FData.FLock);
    end;
    {$ENDIF}
   end;
end;
 
function TJSONEnumerator.Get_Key: WideString;
begin
  if (FIndex<0) or (FData=nil) or (FIndex>=FData.FElementIndex) then
    raise ERangeError.Create('Out of range')
  else
    Result:=FData.FElements[FIndex].Key;
end;
 
function TJSONEnumerator.Get_Value: Variant;
begin
  if (FIndex<0) or (FData=nil) or (FIndex>=FData.FElementIndex) then
    raise ERangeError.Create('Out of range')
  else
    Result:=FData.FElements[FIndex].Value;
end;
 
procedure TJSONEnumerator.Set_Value(const Value: Variant);
begin
  {$IFDEF JSONDOC_THREADSAFE}
  EnterCriticalSection(FData.FLock);
  try
  {$ENDIF}
    if (FIndex<0) or (FData=nil) or (FIndex>=FData.FElementIndex) then
      raise ERangeError.Create('Out of range')
    else
      FData.FElements[FIndex].Value:=Value;
  {$IFDEF JSONDOC_THREADSAFE}
  finally
    LeaveCriticalSection(FData.FLock);
  end;
  {$ENDIF}
end;
 
function TJSONEnumerator.v0: pointer;
begin
  if (FIndex<0) or (FData=nil) or (FIndex>=FData.FElementIndex) then
    raise ERangeError.Create('Out of range')
  else
    Result:=@FData.FElements[FIndex].Value;
end;
 
{ TVarArrayEnumerator }
 
constructor TVarArrayEnumerator.Create(const Data: PVariant);
begin
  inherited Create;
  if VarArrayDimCount(Data^)<>1 then
    raise EJSONException.Create('VarArray: multi-dimensional arrays not supported');
  FData:=Data;
  VarClear(FCurrent);
  FIndex:=VarArrayLowBound(Data^,1);
  FMax:=VarArrayHighBound(Data^,1)+1;
  FCurrentIndex:=FIndex-1;
  if FIndex<FMax then dec(FIndex);//see Next
end;
 
destructor TVarArrayEnumerator.Destroy;
begin
  VarClear(FCurrent);
  FData:=nil;
  inherited;
end;
 
function TVarArrayEnumerator.EOF: boolean;
begin
  Result:=not(FIndex<FMax);
end;
 
function TVarArrayEnumerator.Get_Key: WideString;
begin
  Result:=IntToStr(FIndex);
end;
 
function TVarArrayEnumerator.Get_Value: Variant;
begin
  Result:=FData^[FIndex];
end;
 
function TVarArrayEnumerator.Next: boolean;
begin
  {$IFDEF JSONDOC_THREADSAFE}
  EnterCriticalSection(FLock);
  try
  {$ENDIF}
    inc(FIndex);
    Result:=FIndex<FMax;
  {$IFDEF JSONDOC_THREADSAFE}
  finally
    LeaveCriticalSection(FLock);
  end;
  {$ENDIF}
end;
 
procedure TVarArrayEnumerator.Set_Value(const Value: Variant);
begin
  {$IFDEF JSONDOC_THREADSAFE}
  EnterCriticalSection(FLock);
  try
  {$ENDIF}
    FData^[FIndex]:=Value;
  {$IFDEF JSONDOC_THREADSAFE}
  finally
    LeaveCriticalSection(FLock);
  end;
  {$ENDIF}
end;
 
function TVarArrayEnumerator.v0: pointer;
begin
  {$IFDEF JSONDOC_THREADSAFE}
  EnterCriticalSection(FLock);
  try
  {$ENDIF}
    if FCurrentIndex<>FIndex then
     begin
      FCurrent:=FData^[FIndex];//TODO: keep SafeArray locked for lifetime of TVarArrayEnumerator instance?
      FCurrentIndex:=FIndex;
     end;
    Result:=@FCurrent;
  {$IFDEF JSONDOC_THREADSAFE}
  finally
    LeaveCriticalSection(FLock);
  end;
  {$ENDIF}
end;
 
{ TVarJSONArray }
 
constructor TVarJSONArray.Create(const Data: Variant);
begin
  inherited Create;
  if (TVarData(Data).VType and varArray)=0 then
    raise EJSONException.Create('TVarJSONArray: array variant expected');
  if VarArrayDimCount(Data)<>1 then
    raise EJSONException.Create('TVarJSONArray: multi-dimensional arrays not supported');
  FData:=Data;
  v1:=VarArrayLowBound(FData,1);
  v2:=VarArrayHighBound(FData,1)+1;
  VarClear(FCurrent);
  FCurrentIndex:=-1;
end;
 
constructor TVarJSONArray.CreateNoCopy(var Data: Variant);
begin
  inherited Create;
  if (TVarData(Data).VType and varArray)=0 then
    raise EJSONException.Create('TVarJSONArray: array variant expected');
  if VarArrayDimCount(Data)<>1 then
    raise EJSONException.Create('TVarJSONArray: multi-dimensional arrays not supported');
  VarMove(FData,Data);
  v1:=VarArrayLowBound(FData,1);
  v2:=VarArrayHighBound(FData,1)+1;
  VarClear(FCurrent);
  FCurrentIndex:=-1;
end;
 
destructor TVarJSONArray.Destroy;
begin
  VarClear(FCurrent);
  VarClear(FData);
  inherited;
end;
 
function TVarJSONArray.Count: integer;
begin
  Result:=v2-v1;
end;
 
function TVarJSONArray.Get_Item(Index: integer): Variant;
begin
  if (Index<0) or (Index>=v2-v1) then
    raise ERangeError.Create('Out of range');
  Result:=FData[Index+v1];
end;
 
procedure TVarJSONArray.Set_Item(Index: integer; const Value: Variant);
begin
  {$IFDEF JSONDOC_THREADSAFE}
  EnterCriticalSection(FLock);
  try
  {$ENDIF}
    if (Index<0) or (Index>=v2-v1) then
      raise ERangeError.Create('Out of range');
    FData[Index+v1]:=Value;
  {$IFDEF JSONDOC_THREADSAFE}
  finally
    LeaveCriticalSection(FLock);
  end;
  {$ENDIF}
end;
 
function TVarJSONArray.v0(Index: integer): pointer;
begin
  {$IFDEF JSONDOC_THREADSAFE}
  Result:=nil;//counter warning
  EnterCriticalSection(FLock);
  try
  {$ENDIF}
    if FCurrentIndex<>Index then
     begin
      if (Index<0) or (Index>=v2-v1) then
        raise ERangeError.Create('Out of range');
      FCurrent:=FData[Index+v1];
      FCurrentIndex:=Index;
     end;
    Result:=@FCurrent;
  {$IFDEF JSONDOC_THREADSAFE}
  finally
    LeaveCriticalSection(FLock);
  end;
  {$ENDIF}
end;
 
function TVarJSONArray.JSONToString: WideString;
var
  i:integer;
begin
  {$IFDEF JSONDOC_THREADSAFE}
  EnterCriticalSection(FLock);
  try
  {$ENDIF}
    //TODO: indenting?
    Result:='';
    i:=v1;
    while (i<v2) do
     begin
      Result:=Result+','+JSONVarToStr1(FData[i]);
      inc(i);
     end;
    Result[1]:='[';
    Result:=Result+']';
  {$IFDEF JSONDOC_THREADSAFE}
  finally
    LeaveCriticalSection(FLock);
  end;
  {$ENDIF}
end;
 
{ TJSONArray }
 
constructor TJSONArray.Create(Size: integer);
begin
  inherited Create;
  SetLength(FData,Size);
end;
 
function TJSONArray.Count: integer;
begin
  Result:=Length(FData);
end;
 
function TJSONArray.Get_Item(Index: integer): Variant;
begin
  if (Index<0) or (Index>=Length(FData)) then
    raise ERangeError.Create('Out of range');
  Result:=FData[Index];
end;
 
procedure TJSONArray.Set_Item(Index: integer; const Value: Variant);
begin
  {$IFDEF JSONDOC_THREADSAFE}
  EnterCriticalSection(FLock);
  try
  {$ENDIF}
    if (Index<0) or (Index>=Length(FData)) then
      raise ERangeError.Create('Out of range');
    FData[Index]:=Value;
  {$IFDEF JSONDOC_THREADSAFE}
  finally
    LeaveCriticalSection(FLock);
  end;
  {$ENDIF}
end;
 
function TJSONArray.v0(Index: integer): pointer;
begin
  if (Index<0) or (Index>=Length(FData)) then
    raise ERangeError.Create('Out of range');
  Result:=@FData[Index];
end;
 
function TJSONArray.JSONToString: WideString;
var
  i:integer;
begin
  {$IFDEF JSONDOC_THREADSAFE}
  EnterCriticalSection(FLock);
  try
  {$ENDIF}
    //TODO: indenting?
    Result:='';
    i:=0;
    while (i<Length(FData)) do
     begin
      Result:=Result+','+JSONVarToStr1(FData[i]);
      inc(i);
     end;
    Result[1]:='[';
    Result:=Result+']';
  {$IFDEF JSONDOC_THREADSAFE}
  finally
    LeaveCriticalSection(FLock);
  end;
  {$ENDIF}
end;
 
function TJSONArray.NewEnumerator: IJSONEnumerator;
begin
  Result:=TJSONArrayEnumerator.Create(Self);
end;
 
{ TJSONArrayEnumerator }
 
constructor TJSONArrayEnumerator.Create(const Data: IJSONArray);
begin
  inherited Create;
  FData:=Data;
  FMax:=FData.Count;
  if FMax=0 then FIndex:=0 else FIndex:=-1;//see Next;
end;
 
destructor TJSONArrayEnumerator.Destroy;
begin
  FData:=nil;
  inherited;
end;
 
function TJSONArrayEnumerator.EOF: boolean;
begin
  Result:=not(FIndex<FMax);
end;
 
function TJSONArrayEnumerator.Get_Key: WideString;
begin
  Result:=IntToStr(FIndex);
end;
 
function TJSONArrayEnumerator.Get_Value: Variant;
begin
  Result:=FData[FIndex];
end;
 
function TJSONArrayEnumerator.Next: boolean;
begin
  {$IFDEF JSONDOC_THREADSAFE}
  EnterCriticalSection(FLock);
  try
  {$ENDIF}
    inc(FIndex);
    Result:=FIndex<FMax;
  {$IFDEF JSONDOC_THREADSAFE}
  finally
    LeaveCriticalSection(FLock);
  end;
  {$ENDIF}
end;
 
procedure TJSONArrayEnumerator.Set_Value(const Value: Variant);
begin
  {$IFDEF JSONDOC_THREADSAFE}
  EnterCriticalSection(FLock);
  try
  {$ENDIF}
    FData[FIndex]:=Value;
  {$IFDEF JSONDOC_THREADSAFE}
  finally
    LeaveCriticalSection(FLock);
  end;
  {$ENDIF}
end;
 
function TJSONArrayEnumerator.v0: pointer;
begin
  Result:=FData.v0(FIndex);
end;
 
{ TJSONDocArray }
 
constructor TJSONDocArray.Create;
begin
  inherited Create;
  FItemsCount:=0;
  FItemsSize:=0;
end;
 
destructor TJSONDocArray.Destroy;
begin
  SetLength(FItems,0);
  inherited;
end;
 
function TJSONDocArray.Get_Item(Index: integer): Variant;
begin
  {$IFDEF JSONDOC_THREADSAFE}
  EnterCriticalSection(FLock);
  try
  {$ENDIF}
    if (Index<0) or (Index>=FItemsCount) then
      raise ERangeError.Create('Index out of range');
    //parse from string here assuming this won't be needed much
    if FItems[Index]='null' then
      Result:=Null
    else
      Result:=JSON(FItems[Index]);
  {$IFDEF JSONDOC_THREADSAFE}
  finally
    LeaveCriticalSection(FLock);
  end;
  {$ENDIF}
end;
 
function TJSONDocArray.v0(Index: integer): pointer;
begin
  {$IFDEF JSONDOC_THREADSAFE}
  Result:=nil;//counter warning
  EnterCriticalSection(FLock);
  try
  {$ENDIF}
    if FCurrentIndex<>Index then
     begin
      if (Index<0) or (Index>=FItemsCount) then
        raise ERangeError.Create('Index out of range');
      //parse from string here assuming this won't be needed much
      if FItems[Index]='null' then
        FCurrent:=Null
      else
        FCurrent:=JSON(FItems[Index]);
      FCurrentIndex:=Index;
     end;
    Result:=@FCurrent;
  {$IFDEF JSONDOC_THREADSAFE}
  finally
    LeaveCriticalSection(FLock);
  end;
  {$ENDIF}
end;
 
procedure TJSONDocArray.Set_Item(Index: integer; const Value: Variant);
var
  d:IJSONDocument;
begin
  {$IFDEF JSONDOC_THREADSAFE}
  EnterCriticalSection(FLock);
  try
  {$ENDIF}
    if (Index<0) or (Index>=FItemsCount) then
      raise ERangeError.Create('Index out of range');
    case TVarData(Value).VType of
      varNull:
        FItems[Index]:='null';
      varUnknown:
        if (TVarData(Value).VUnknown<>nil) and
          (IUnknown(Value).QueryInterface(IID_IJSONDocument,d)=S_OK) then
          FItems[Index]:=d.ToString
        else raise EJSONEncodeException.Create(
          'JSONDocArray.Set_Item requires IJSONDocument instances');
      else raise EJSONEncodeException.Create(
        'JSONDocArray.Set_Item requires IJSONDocument instances');
    end;
  {$IFDEF JSONDOC_THREADSAFE}
  finally
    LeaveCriticalSection(FLock);
  end;
  {$ENDIF}
end;
 
function TJSONDocArray.Count: integer;
begin
  Result:=FItemsCount;
end;
 
procedure TJSONDocArray.Clear;
var
  i:integer;
begin
  {$IFDEF JSONDOC_THREADSAFE}
  EnterCriticalSection(FLock);
  try
  {$ENDIF}
    for i:=0 to FItemsCount-1 do FItems[i]:='';
    FItemsCount:=0;
  {$IFDEF JSONDOC_THREADSAFE}
  finally
    LeaveCriticalSection(FLock);
  end;
  {$ENDIF}
end;
 
function TJSONDocArray.Add(const Doc: IJSONDocument): integer;
begin
  {$IFDEF JSONDOC_THREADSAFE}
  EnterCriticalSection(FLock);
  try
  {$ENDIF}
    if FItemsCount=FItemsSize then
     begin
      inc(FItemsSize,$400);//grow
      SetLength(FItems,FItemsSize);
     end;
    //ToString here to save on persisting effort later
    if Doc=nil then
      FItems[FItemsCount]:='null'
    else
      FItems[FItemsCount]:=Doc.ToString;
    Result:=FItemsCount;
    inc(FItemsCount);
  {$IFDEF JSONDOC_THREADSAFE}
  finally
    LeaveCriticalSection(FLock);
  end;
  {$ENDIF}
end;
 
function TJSONDocArray.AddJSON(const Data: WideString): integer;
begin
  {$IFDEF JSONDOC_THREADSAFE}
  EnterCriticalSection(FLock);
  try
  {$ENDIF}
    if FItemsCount=FItemsSize then
     begin
      inc(FItemsSize,$400);//grow
      SetLength(FItems,FItemsSize);
     end;
    //TODO: check valid JSON?
    FItems[FItemsCount]:=Data;
    Result:=FItemsCount;
    inc(FItemsCount);
  {$IFDEF JSONDOC_THREADSAFE}
  finally
    LeaveCriticalSection(FLock);
  end;
  {$ENDIF}
end;
 
procedure TJSONDocArray.LoadItem(Index: integer; const Doc: IJSONDocument);
begin
  {$IFDEF JSONDOC_THREADSAFE}
  EnterCriticalSection(FLock);
  try
  {$ENDIF}
    if (Index<0) or (Index>=FItemsCount) then
      raise ERangeError.Create('Index out of range');
    Doc.Clear;
    if FItems[Index]<>'null' then Doc.Parse(FItems[Index]);
    //else?
  {$IFDEF JSONDOC_THREADSAFE}
  finally
    LeaveCriticalSection(FLock);
  end;
  {$ENDIF}
end;
 
function TJSONDocArray.GetJSON(Index: integer): WideString; stdcall;
begin
  {$IFDEF JSONDOC_THREADSAFE}
  EnterCriticalSection(FLock);
  try
  {$ENDIF}
    if (Index<0) or (Index>=FItemsCount) then
      raise ERangeError.Create('Index out of range');
    Result:=FItems[Index];
    //else?
  {$IFDEF JSONDOC_THREADSAFE}
  finally
    LeaveCriticalSection(FLock);
  end;
  {$ENDIF}
end;
 
function TJSONDocArray.JSONToString: WideString;
var
  i,x,l:integer;
begin
  {$IFDEF JSONDOC_THREADSAFE}
  EnterCriticalSection(FLock);
  try
  {$ENDIF}
    if FItemsCount=0 then
      Result:='[]'
    else
     begin
      l:=FItemsCount+1;
      for i:=0 to FItemsCount-1 do
        inc(l,Length(FItems[i]));
      SetLength(Result,l);
      i:=0;
      x:=1;
      while i<FItemsCount do
       begin
        Result[x]:=',';
        inc(x);
        l:=Length(FItems[i]);
        Move(FItems[i][1],Result[x],l*2);
        inc(x,l);
        inc(i);
       end;
      Result[1]:='[';
      Result[x]:=']';
     end;
  {$IFDEF JSONDOC_THREADSAFE}
  finally
    LeaveCriticalSection(FLock);
  end;
  {$ENDIF}
end;
 
{ JSON }
 
function JSON:IJSONDocument; //overload;
begin
  Result:=TJSONDocument.Create as IJSONDocument;
end;
 
function JSON(const x:array of Variant):IJSONDocument; //overload;
var
  i,l,si,sl:integer;
  s:array of TJSONDocument;
  d:TJSONDocument;
  key:WideString;
begin
  d:=TJSONDocument.Create;
  si:=0;
  sl:=0;
  i:=0;
  l:=Length(x);
  while i<l do
   begin
    key:=VarToWideStr(x[i]);
    inc(i);
    if (key<>'') and (key[1]='}') then
     begin
      while (key<>'') and (key[1]='}') do
       begin
        //pop from stack
        if si=0 then
          raise EJSONException.Create('JSON builder: closing more embedded documents than opened #'+IntToStr(i))
        else
         begin
          dec(si);
          d:=s[si];
          s[si]:=nil;
         end;
        key:=Copy(key,2,Length(key)-1);
       end;
      if key<>'' then
        raise EJSONException.Create('JSON builder: "}" not allowed as key prefix #'+IntToStr(i));
     end
    else
      if (key<>'') and (key[Length(key)]='{') then
       begin
        //push on stack
        if si=sl then
         begin
          inc(sl,8);//growstep
          SetLength(s,sl);
         end;
        s[si]:=d;
        d:=TJSONDocument.Create;
        s[si][Copy(key,1,Length(key)-1)]:=d as IJSONDocument;
        inc(si);
       end
      else
        if i=l then
          raise EJSONException.Create('JSON builder: last key is missing value')
        else
         begin
          d[key]:=x[i];
          inc(i);
         end;
   end;
  //any left open?
  if si=0 then Result:=d else Result:=s[si-1];
end;
 
function JSON(const x: Variant): IJSONDocument; overload;
begin
  case TVarData(x).VType of
    varNull,varEmpty:Result:=nil;//raise?
    varOleStr,varString,$0102:
     begin
      Result:=TJSONDocument.Create as IJSONDocument;
      Result.Parse(VarToWideStr(x));
     end;
    else
      Result:=IUnknown(x) as IJSONDocument;
  end;
end;
 
function JSONEnum(const x: IJSONDocument): IJSONEnumerator;
var
  je:IJSONEnumerable;
begin
  if x=nil then
    Result:=TJSONEnumerator.Create(nil)
  else
    //Result:=(x as IJSONEnumerable).NewEnumerator;
    if x.QueryInterface(IID_IJSONEnumerable,je)=S_OK then
      Result:=je.NewEnumerator
    else
      raise EJSONException.Create('IJSONDocument instance doesn''t implement IJSONEnumerable');
end;
 
function JSONEnum(const x: Variant): IJSONEnumerator;
var
  vt:TVarType;
  e:IJSONEnumerable;
begin
  vt:=TVarData(x).VType;
  if (vt and varArray)=0 then
    case vt of
      varNull,varEmpty:
        Result:=TJSONEnumerator.Create(nil);//has .EOF=true
      varUnknown:
        if (TVarData(x).VUnknown<>nil) and
          (IUnknown(x).QueryInterface(IID_IJSONEnumerable,e)=S_OK) then
          Result:=e.NewEnumerator
        else
          raise EJSONException.Create('No supported interface found on object');
      else
        raise EJSONException.Create('Unsupported variant type '+IntToHex(vt,4));
    end
  else
    Result:=TVarArrayEnumerator.Create(@x);
end;
 
function JSON(const x: IJSONEnumerator): IJSONDocument;
begin
  Result:=IUnknown(x.Value) as IJSONDocument;
end;
 
function JSONEnum(const x: IJSONEnumerator): IJSONEnumerator;
begin
  if (x=nil) or VarIsNull(x.Value) then
    Result:=TJSONEnumerator.Create(nil)
  else
    Result:=(IUnknown(x.Value) as IJSONEnumerable).NewEnumerator;
end;
 
function ja(const Items:array of Variant): IJSONArray;
var
  a:TJSONArray;
  i,l:integer;
begin
  l:=Length(Items);
  a:=TJSONArray.Create(l);
  i:=0;
  while i<>l do
   begin
    a.FData[i]:=Items[i];
    inc(i);
   end;
  Result:=a;
end;
 
function ja(const Item:Variant): IJSONArray;
begin
  if (TVarData(Item).VType=varUnknown) and
    (TVarData(Item).VUnknown<>nil) and
    (IUnknown(Item).QueryInterface(IID_IJSONArray,Result)=S_OK) then
    //ok!
  else
  if (TVarData(Item).VType and varArray)<>0 then
    Result:=TVarJSONArray.Create(Item)
  else
    raise EJSONException.Create('Variant is not IJSONArray');
end;
 
function JSONDocArray: IJSONDocArray;
begin
  Result:=TJSONDocArray.Create;
end;
 
function JSONDocArray(const Items:array of IJSONDocument): IJSONDocArray;
var
  i:integer;
begin
  Result:=TJSONDocArray.Create;
  for i:=0 to Length(Items)-1 do Result.Add(Items[i]);
end;
 
initialization
  {$IFDEF JSONDOC_DEFAULT_USE_IJSONARRAY}
  JSON_UseIJSONArray:=true//default, see TJSONDocument.Create
  {$ELSE}
  JSON_UseIJSONArray:=false; //default, see TJSONDocument.Create
  {$ENDIF}
end.

  

posted @   delphi中间件  阅读(399)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
历史上的今天:
2016-09-08 FDMemTable的详细使用方法
点击右上角即可分享
微信分享提示