vibe.data.json 164/959(17%) line coverage

      
10
20
30
40
50
60
70
80
90
100
110
120
130
140
150
160
170
180
190
200
210
220
230
240
250
260
270
280
290
300
310
320
330
340
350
360
370
380
390
400
410
420
430
440
450
460
470
480
490
500
510
520
530
540
550
560
570
580
590
600
610
620
630
640
650
660
670
680
690
700
710
720
730
740
750
760
770
780
790
800
810
820
830
840
850
860
870
880
890
900
910
920
930
940
950
960
970
980
990
1000
1010
1020
1030
1040
1050
1060
1070
1080
1090
1100
1110
1120
1130
1140
1150
1160
1170
1180
1190
1200
12154
1220
1230
1240
1252
1260
1270
12813
12938
1301
1310
1320
1330
1340
1350
1360
1370
1380
1390
1400
1410
1420
1430
1440
1450
1460
1470
1480
1490
1500
1510
1520
1530
1540
1550
1560
1570
1580
1590
1600
1610
1620
1630
1641
1650
1660
1672
1680
1690
1701
1710
1720
1730
1740
1750
1760
1770
1780
1790
1800
1810
1820
1830
1840
1850
1860
1870
1880
1890
1900
1910
1920
1930
1940
1950
1960
1970
1980
1993
2000
2013
2020
2036
2040
2050
2060
2070
2080
2090
2103
2113
2123
2133
2143
2153
2160
2170
2180
2190
2200
2210
2220
2230
2240
2250
2260
2276
2280
2293
2300
2310
2320
2330
2340
2350
2368
2370
2380
2390
2400
2410
2420
2430
2440
2450
2460
2470
2480
2490
2500
25112
2520
2530
2540
2550
2560
2570
2580
2590
2600
2610
2620
2630
2640
2650
2660
2670
2685
2695
2705
2710
2725
2730
2740
2750
2760
2770
2780
2790
2800
2810
2820
28330
2840
2850
2860
2870
2880
2890
2900
2910
2920
2930
2940
2950
2960
2970
2980
2990
3000
3010
3020
3030
3040
3050
3060
3070
3080
3090
3100
3110
3120
3130
3140
3150
3160
3170
3180
3190
3200
3210
3220
3230
3240
3250
3260
3270
3280
3290
3300
3310
3320
3330
3340
3350
3360
3370
3380
3390
3400
3410
3420
3430
3444
3454
3462
3472
3481
3491
3500
3514
3522
3532
3542
3552
3562
3570
3582
3590
3600
3610
3620
3630
3640
3650
3660
3670
3680
3690
3700
3710
3720
3730
3740
3750
3760
3770
3780
3790
3800
3810
3820
3830
3840
3851
3861
3870
3880
3892
3900
3910
3920
3930
3940
3950
3960
3970
3980
3990
4000
4010
4020
4030
4040
4050
4060
4070
4080
4090
4100
4110
4120
4130
4140
4150
4160
4170
4180
4190
4200
4210
4220
4230
4240
4250
4260
4270
4280
4290
4300
4310
4320
4330
4340
4350
4360
4370
4380
4390
4400
4410
4420
4430
4440
4450
4460
4470
4480
4490
4500
4513
4523
4534
4544
4550
4563
4570
4580
4590
4600
4610
4620
4630
4640
4650
4660
4670
4680
4690
4700
4710
4720
4730
4749
4750
4760
4770
4780
4790
4800
4810
4820
4830
4840
4850
4860
4870
4880
4890
4900
4910
4920
4930
4940
4950
4960
4970
4980
4990
5000
5010
5020
5030
5040
5050
5060
5070
5080
5090
5100
5110
5120
5130
5140
5150
5160
5170
5180
5190
5200
5210
5220
5230
5240
5250
5260
5270
5280
5290
5300
5310
5320
5330
5340
5350
5360
5370
5380
5390
5400
5413
5420
5430
5440
5450
5463
5470
5480
5490
5500
5510
5520
5530
5540
5550
5560
5570
5580
5590
5600
5610
5620
5630
5640
5650
5660
5670
5680
5690
5700
5710
5720
5730
5740
5750
5760
5770
5780
5790
5800
5810
5820
5830
5840
5850
5860
5870
5880
5890
5900
5910
5920
5930
5940
5950
5960
5970
5980
5990
6000
6010
6020
6030
6040
6050
6060
6070
6080
6090
6100
6110
6120
6130
6140
6150
6160
6170
6180
6190
6200
6210
6220
6230
6240
6250
6260
6270
6280
6290
6300
6310
6320
6330
6340
6350
6360
6370
6380
6390
6400
6410
6420
6430
6440
6450
6460
6470
6480
6490
6500
6510
6520
6530
6543
6550
6566
6570
6580
6590
6600
6610
6620
6630
6640
6650
6660
6670
6680
6690
6700
6710
6720
6730
6740
6750
6760
6770
6780
6790
6800
6810
6820
6830
6840
6850
6860
6870
6880
6890
6900
6910
6920
6930
6940
6950
6960
6970
6980
6990
7000
7010
7020
7030
7040
7050
7060
7070
7080
7090
7100
7110
7120
7130
7140
7150
7160
7170
7180
7190
7200
7210
7220
7230
7240
7250
7260
7270
7280
7290
7300
7310
7320
7330
7340
7350
7360
7370
7380
7390
7400
7410
7420
7430
7440
7450
7460
7470
7480
7490
7500
7510
7520
7530
7540
7550
7560
7570
7580
7590
7600
7610
7620
7630
7640
7650
7660
7670
7680
7690
7700
7710
7720
7730
7740
7750
7760
7770
7780
7790
7800
7810
7820
7830
7840
7850
7860
7870
7880
7890
7900
7910
7920
7930
7940
7950
7960
7970
7980
7990
8000
8010
8020
8030
8040
8050
8060
8070
8080
8090
8100
8110
8120
8130
8140
8150
8160
8170
8180
8190
8200
8210
8220
8230
8240
8250
8260
8270
8280
8290
8300
8310
8320
8330
8340
8350
8360
8370
8380
8390
8400
8410
8420
8430
8440
8450
8460
8470
8480
8490
8500
8510
8520
8530
8540
8550
8560
8570
8580
8590
8600
8610
8620
8630
8640
8650
8660
8670
8680
8690
8700
8710
8720
8730
8740
8750
8760
8770
8780
8790
8800
8810
8820
8830
8840
8850
8860
8870
8880
8890
8900
8910
8920
8930
8940
8950
8960
8970
8980
8990
9000
9010
9020
9030
9040
9050
9060
9070
9080
9090
9100
9110
9120
9130
9140
9150
9160
9170
9180
9190
9200
9210
9220
9230
9240
9250
9260
9270
9280
9290
9300
9310
9320
9330
9340
9350
9360
9370
9380
9390
9400
9410
9420
9430
9440
9450
9460
9470
9480
9490
9500
9510
9520
9530
9540
9550
9560
9570
9580
9590
9600
9610
9620
9630
9640
9650
9660
9670
9680
9690
9700
9710
9720
9730
9740
9750
9760
9770
9780
9790
9800
9810
9820
9830
9840
9850
9860
9870
9880
9890
9900
9910
9920
9930
9940
9950
9960
9970
9980
9990
10004
10011
100211
10030
10040
10050
10060
10070
10080
10090
10100
10110
10120
10130
10140
10150
10160
10170
10180
10190
10200
10210
10220
10230
10240
10250
10260
10270
10280
10290
10300
10310
10320
10330
10340
10350
10360
10370
10380
10390
10400
10410
10420
10430
10440
10450
10460
10470
10480
10490
10500
10510
10520
10530
10540
10550
10560
10570
10580
10590
10600
10610
10620
10630
10640
10650
10660
10670
10680
10690
10700
10710
10721
10731
10741
10750
10760
10770
10780
107914
108046
108128
10820
10830
10840
10850
10860
10870
10880
10890
10900
10910
10920
10930
10940
10950
10960
10970
10980
10990
11000
11010
11020
11030
11040
11050
11060
11070
11080
11090
11100
11110
11120
111326
11140
11150
11160
11170
11180
11190
11200
11210
11220
11230
11240
11250
11260
11270
11280
11290
11300
11310
11320
11330
11340
11350
11360
11370
11380
11390
11400
11410
11420
11430
11440
11450
11460
11470
11480
11490
11500
11510
11520
11530
11540
11550
11560
11570
11586
11596
11600
11616
11620
11636
11640
11650
11660
11670
11680
11696
11706
11710
11720
11730
11740
11750
11760
11770
11780
11790
11800
11810
11820
11830
11840
11850
11860
11870
11880
11890
11900
11910
11920
11930
11940
11950
11960
11970
11980
11990
12003
12013
12023
12030
12040
12050
12060
12070
12080
12090
12100
12110
12120
12130
12140
12150
12160
12170
12180
12190
12200
12213
12223
12233
12243
12253
12263
12273
12283
12293
12303
12313
12323
12333
12346
12353
12363
12376
12380
12396
12400
12410
12423
12433
12443
12450
12460
12470
12480
12490
12506
12510
12526
12530
12540
12550
12560
12570
12580
12590
12600
12610
12622
12632
12644
12652
12662
12670
12680
12690
12700
12710
12720
12730
12740
12750
12760
12770
12780
12790
12800
12810
12820
12830
12840
12850
12860
12870
12880
12890
12900
12910
12920
12930
12940
12950
12960
12970
12980
12990
13000
13010
13020
13030
13040
13050
13060
13070
13080
13090
13100
13110
13120
13130
13140
13150
13160
13170
13180
13190
13200
13210
13220
13230
13240
13250
13260
13270
13280
13290
13300
13310
13320
13330
13340
13350
13360
13370
13380
13390
13400
13410
13420
13430
13440
13450
13460
13470
13480
13490
13500
13510
13520
13530
13540
13550
13560
13570
13580
13590
13600
13610
13620
13630
13640
13652
13660
13670
13680
13690
13700
13710
13720
13730
13740
13750
13760
13770
13780
13790
13800
13810
13820
13830
13840
13850
13860
13870
13880
13890
13900
13910
13920
13930
13940
13950
13960
13970
13980
13990
14000
14010
14020
14030
14040
14050
14060
14070
14080
14090
14100
14110
14120
14130
14140
14150
14160
14170
14180
14190
14200
14210
14220
14230
14240
14250
14260
14270
14280
14290
14300
14310
14320
14330
14340
14350
14360
14370
14380
14390
14400
14410
14420
14430
14440
14450
14460
14470
14480
14490
14500
14510
14520
14530
14540
14550
14560
14570
14580
14590
14600
14610
14620
14630
14640
14650
14660
14670
14680
14690
14700
14710
14720
14730
14740
14750
14760
14770
14780
14790
14800
14810
14820
14830
14840
14850
14860
14870
14880
14890
14900
14910
14920
14930
14940
14950
14960
14970
14980
14990
15000
15010
15020
15030
15040
15050
15060
15070
15080
15090
15100
15110
15120
15130
15140
15150
15160
15170
15180
15190
15200
15210
15220
15230
15240
15250
15260
15270
15280
15290
15300
15310
15320
15330
15340
15350
15360
15370
15380
15390
15400
15410
15420
15430
15440
15450
15460
15470
15480
15490
15500
15510
15520
15530
15540
15550
15560
15570
15580
15590
15600
15610
15620
15630
15640
15650
15660
15670
15680
15690
15700
15710
15720
15730
15740
15750
15760
15770
15780
15790
15800
15810
15820
15830
15840
15850
15860
15870
15880
15890
15900
15910
15920
15930
15940
15950
15960
15970
15980
15990
16000
16010
16020
16030
16040
16050
16060
16070
16080
16090
16100
16110
16120
16130
16140
16150
16160
16170
16180
16190
16200
16210
16220
16230
16240
16250
16260
16270
16280
16290
16300
16310
16320
16330
16340
16350
16360
16370
16380
16390
16400
16410
16420
16430
16440
16450
16460
16470
16480
16490
16500
16510
16520
16530
16540
16550
16560
16570
16580
16590
16600
16610
16620
16630
16640
16650
16660
16670
16680
16690
16700
16710
16720
16730
16740
16750
16760
16770
16780
16790
16800
16810
16820
16830
16840
16850
16860
16870
16880
16890
16900
16910
16920
16930
16940
16950
16960
16970
16980
16990
17000
17010
17020
17030
17040
17050
17060
17070
17080
17090
17100
17110
17120
17130
17140
17150
17160
17170
17180
17190
17200
17210
17220
17230
17240
17250
17260
17270
17280
17290
17300
17310
17320
17330
17340
17350
17360
17370
17380
17390
17400
17410
17420
17430
17440
17450
17460
17470
17480
17490
17500
17510
17520
17530
17540
17550
17560
17570
17580
17590
17600
17610
17620
17630
17640
17650
17660
17670
17680
17692
17700
17712
17720
17730
17740
17750
17760
17770
17780
17790
17800
17810
17820
17830
17840
17850
17860
17870
17880
17890
17900
17910
17920
17930
17940
17950
17960
17970
17980
17990
18000
18010
18020
18030
18040
18050
18060
18070
18080
18090
18100
18110
18120
18130
18140
18152
18160
18170
18180
18190
18200
18210
18220
18230
18240
18250
18260
18270
18280
18290
18300
18310
18320
18330
18340
18350
18360
18370
18380
18390
18400
18410
18420
18430
18440
18450
18460
18470
18480
18490
18500
18510
18520
18530
18540
18550
18560
18570
18580
18590
18600
18610
18620
18630
18640
18650
18660
18670
18680
18690
18700
18710
18720
18730
18740
18750
18760
18770
18780
18790
18800
18810
18820
18830
18840
18850
18860
18870
18880
18890
18900
18910
18920
18930
18940
18950
18960
18970
18980
18990
19000
19010
19020
19030
19040
19050
19060
19070
19080
19090
19100
19110
19120
19130
19140
19150
19160
19170
19180
19190
19200
19210
19220
19230
19240
19250
19260
19270
19280
19290
19300
19310
19320
19330
19340
19350
19360
19370
19380
19390
19400
19410
19420
19430
19440
19450
19460
19470
19480
19490
19500
19510
19520
19530
19540
19550
19560
19570
19580
19590
19600
19610
19620
19630
19640
19650
19660
19670
19680
19690
19700
19710
19720
19730
19740
19750
19760
19770
19780
19790
19800
19810
19820
19830
19840
19850
19860
19870
19880
19890
19900
19910
19920
19930
19940
19950
19960
19970
19980
19996
20000
20010
20020
20030
20040
20050
20060
20070
20080
20090
20100
20110
20123
20133
20143
20153
20163
20170
20180
20190
20200
20210
20220
20230
20240
20250
20260
20270
20280
20290
20300
20310
20320
20330
20340
20350
20360
20370
20383
20393
20403
204121
20423
20433
20443
20450
20461
20477
20480
20493
20503
20513
20523
20530
20540
20551
20561
20573
20580
20590
20603
20613
20620
20630
20640
20650
20660
20670
20680
20690
20700
20710
20720
20730
20740
20750
20760
20770
20780
20790
20800
20810
20820
20830
20840
20850
20860
20870
20880
20890
20900
20910
20920
20930
20940
20950
20960
20970
20980
20990
21000
21010
21020
21030
21040
21050
21060
21070
21080
21090
21100
21110
21120
21130
21140
21150
21160
21170
21180
21190
21200
21210
21220
21230
21240
21250
21260
21270
21280
21290
21300
21310
21320
21330
21340
21350
21360
21370
21380
21390
21400
21410
21420
21430
21440
21450
21460
21470
21480
21491
21500
21510
21520
21530
21540
21550
21560
21570
21580
21590
21600
21610
21620
21630
21640
21650
21660
21676
216860
216924
21700
217124
217224
21730
21740
21750
21760
21770
21780
21790
21800
21810
21820
21830
21840
21850
21860
21870
21880
21890
21900
21910
21920
21930
21940
21950
21960
21970
21980
21990
220024
220124
22020
220324
22040
22050
22060
22070
22080
22090
22100
22110
22120
22130
22140
22150
221624
22170
22180
22190
22200
22210
22220
22236
222430
222530
222630
222712
22280
22290
22300
22310
22320
22330
22340
22350
22360
22370
22380
22390
22400
22410
22420
22430
22440
22450
22460
22470
22480
22490
22500
22510
22520
22530
22540
22550
22560
22570
22580
22590
22600
22610
22620
22630
22640
22650
22660
22670
22680
22690
22700
22710
22720
22730
22740
22750
22760
22770
22780
22790
228024
228124
228224
228324
22840
22850
22860
22870
22880
22890
22900
22910
22920
22930
22940
22950
22960
22970
22980
22990
23000
23010
23020
23030
23040
23050
23060
23070
23080
23090
23100
23110
23120
23130
23140
23150
23160
23170
23180
23190
23200
23210
23220
23230
23240
23250
23260
23270
23280
23290
23300
23310
23320
23330
23340
23350
23360
23370
23380
23390
23400
23410
23420
23430
23440
23450
23460
23470
23480
23490
23500
23510
23520
23530
23540
23550
23560
23570
23580
23590
23600
23610
23620
23630
23640
23650
23660
23670
23680
23690
23700
23710
23720
23730
23740
23750
23760
23770
23780
23790
23800
23810
238212
23836
23846
238512
23866
23876
23880
23890
23900
23910
23920
239323
239423
239536
239620
23970
23980
23990
24000
24010
24020
24030
24040
24050
24060
24070
24080
24090
24100
24110
24120
24130
24140
24150
24160
24170
24180
24190
24200
24210
24220
24230
242412
24250
24260
24270
24280
242926
24300
24310
24320
24330
243424
24350
24360
24370
24380
24393
24400
24416
24423
24433
24440
24453
24460
24470
24480
24490
24500
24510
24520
24530
24540
24550
24560
24570
24580
24590
24600
24610
24620
24630
24640
24650
24660
24670
24680
24690
24700
24710
24720
24730
24740
24750
24760
24770
24780
24790
24800
24810
24820
24830
24840
24850
24860
24870
24880
24890
24900
24910
24920
24930
24940
24950
24960
24970
24980
24990
25000
25010
25020
25030
25040
/** JSON serialization and value handling. This module provides the Json struct for reading, writing and manipulating JSON values. De(serialization) of arbitrary D types is also supported and is recommended for handling JSON in performance sensitive applications. Copyright: © 2012-2015 RejectedSoftware e.K. License: Subject to the terms of the MIT license, as written in the included LICENSE.txt file. Authors: Sönke Ludwig */ module vibe.data.json; /// @safe unittest { void manipulateJson(Json j) { import std.stdio; // retrieving the values is done using get() assert(j["name"].get!string == "Example"); assert(j["id"].get!int == 1); // semantic conversions can be done using to() assert(j["id"].to!string == "1"); // prints: // name: "Example" // id: 1 foreach (key, value; j.byKeyValue) writefln("%s: %s", key, value); // print out as JSON: {"name": "Example", "id": 1} writefln("JSON: %s", j.toString()); // DEPRECATED: object members can be accessed using member syntax, just like in JavaScript //j = Json.emptyObject; //j.name = "Example"; //j.id = 1; } } /// Constructing `Json` objects @safe unittest { // construct a JSON object {"field1": "foo", "field2": 42, "field3": true} // using the constructor Json j1 = Json(["field1": Json("foo"), "field2": Json(42), "field3": Json(true)]); // using piecewise construction Json j2 = Json.emptyObject; j2["field1"] = "foo"; j2["field2"] = 42.0; j2["field3"] = true; // using serialization struct S { string field1; double field2; bool field3; } Json j3 = S("foo", 42, true).serializeToJson(); // using serialization, converting directly to a JSON string string j4 = S("foo", 32, true).serializeToJsonString(); } public import vibe.data.serialization; public import std.json : JSONException; import std.algorithm; import std.array; import std.conv; import std.datetime; import std.exception; import std.format; import std.string; import std.range; import std.traits; import std.typecons : Tuple; import std.bigint; /******************************************************************************/ /* public types */ /******************************************************************************/ /** Represents a single JSON value. Json values can have one of the types defined in the Json.Type enum. They behave mostly like values in ECMA script in the way that you can transparently perform operations on them. However, strict typechecking is done, so that operations between differently typed JSON values will throw a JSONException. Additionally, an explicit cast or using get!() or to!() is required to convert a JSON value to the corresponding static D type. */ align(8) // ensures that pointers stay on 64-bit boundaries on x64 so that they get scanned by the GC struct Json { @safe: static assert(!hasElaborateDestructor!BigInt && !hasElaborateCopyConstructor!BigInt, "struct Json is missing required ~this and/or this(this) members for BigInt."); private { // putting all fields in a union results in many false pointers leading to // memory leaks and, worse, std.algorithm.swap triggering an assertion // because of internal pointers. This crude workaround seems to fix // the issues. enum m_size = max((BigInt.sizeof+(void*).sizeof), 2); // NOTE : DMD 2.067.1 doesn't seem to init void[] correctly on its own. // Explicity initializing it works around this issue. Using a void[] // array here to guarantee that it's scanned by the GC. void[m_size] m_data = (void[m_size]).init; static assert(m_data.offsetof == 0, "m_data must be the first struct member."); static assert(BigInt.alignof <= 8, "Json struct alignment of 8 isn't sufficient to store BigInt."); ref inout(T) getDataAs(T)() inout @trusted { static assert(T.sizeof <= m_data.sizeof); return (cast(inout(T)[1])m_data[0 .. T.sizeof])[0]; } @property ref inout(BigInt) m_bigInt() inout { return getDataAs!BigInt(); } @property ref inout(long) m_int() inout { return getDataAs!long(); } @property ref inout(double) m_float() inout { return getDataAs!double(); } @property ref inout(bool) m_bool() inout { return getDataAs!bool(); } @property ref inout(string) m_string() inout { return getDataAs!string(); } @property ref inout(Json[string]) m_object() inout { return getDataAs!(Json[string])(); } @property ref inout(Json[]) m_array() inout { return getDataAs!(Json[])(); } Type m_type = Type.undefined; version (VibeJsonFieldNames) { uint m_magic = 0x1337f00d; // works around Appender bug (DMD BUG 10690/10859/11357) string m_name; } } /** Represents the run time type of a JSON value. */ enum Type { undefined, /// A non-existent value in a JSON object null_, /// Null value bool_, /// Boolean value int_, /// 64-bit integer value bigInt, /// BigInt values float_, /// 64-bit floating point value string, /// UTF-8 string array, /// Array of JSON values object, /// JSON object aka. dictionary from string to Json Undefined = undefined, /// Compatibility alias - will be deprecated soon Null = null_, /// Compatibility alias - will be deprecated soon Bool = bool_, /// Compatibility alias - will be deprecated soon Int = int_, /// Compatibility alias - will be deprecated soon Float = float_, /// Compatibility alias - will be deprecated soon String = string, /// Compatibility alias - will be deprecated soon Array = array, /// Compatibility alias - will be deprecated soon Object = object /// Compatibility alias - will be deprecated soon } /// New JSON value of Type.Undefined static @property Json undefined() { return Json(); } /// New JSON value of Type.Object static @property Json emptyObject() { return Json(cast(Json[string])null); } /// New JSON value of Type.Array static @property Json emptyArray() { return Json(cast(Json[])null); } version(JsonLineNumbers) int line; /** Constructor for a JSON object. */ this(typeof(null)) @trusted { m_type = Type.null_; } /// ditto this(bool v) @trusted { m_type = Type.bool_; m_bool = v; } /// ditto this(byte v) { this(cast(long)v); } /// ditto this(ubyte v) { this(cast(long)v); } /// ditto this(short v) { this(cast(long)v); } /// ditto this(ushort v) { this(cast(long)v); } /// ditto this(int v) { this(cast(long)v); } /// ditto this(uint v) { this(cast(long)v); } /// ditto this(long v) @trusted { m_type = Type.int_; m_int = v; } /// ditto this(BigInt v) @trusted { m_type = Type.bigInt; initBigInt(); m_bigInt = v; } /// ditto this(double v) @trusted { m_type = Type.float_; m_float = v; } /// ditto this(string v) @trusted { m_type = Type.string; m_string = v; } /// ditto this(Json[] v) @trusted { m_type = Type.array; m_array = v; } /// ditto this(Json[string] v) @trusted { m_type = Type.object; m_object = v; } /** Allows assignment of D values to a JSON value. */ ref Json opAssign(Json v) { if (v.type != Type.bigInt) runDestructors(); auto old_type = m_type; m_type = v.m_type; final switch(m_type){ case Type.undefined: m_string = null; break; case Type.null_: m_string = null; break; case Type.bool_: m_bool = v.m_bool; break; case Type.int_: m_int = v.m_int; break; case Type.bigInt: if (old_type != Type.bigInt) initBigInt(); m_bigInt = v.m_bigInt; break; case Type.float_: m_float = v.m_float; break; case Type.string: m_string = v.m_string; break; case Type.array: opAssign(v.m_array); break; case Type.object: opAssign(v.m_object); break; } return this; } /// ditto void opAssign(typeof(null)) { runDestructors(); m_type = Type.null_; m_string = null; } /// ditto bool opAssign(bool v) { runDestructors(); m_type = Type.bool_; m_bool = v; return v; } /// ditto int opAssign(int v) { runDestructors(); m_type = Type.int_; m_int = v; return v; } /// ditto long opAssign(long v) { runDestructors(); m_type = Type.int_; m_int = v; return v; } /// ditto BigInt opAssign(BigInt v) { if (m_type != Type.bigInt) initBigInt(); m_type = Type.bigInt; m_bigInt = v; return v; } /// ditto double opAssign(double v) { runDestructors(); m_type = Type.float_; m_float = v; return v; } /// ditto string opAssign(string v) { runDestructors(); m_type = Type.string; m_string = v; return v; } /// ditto Json[] opAssign(Json[] v) { runDestructors(); m_type = Type.array; m_array = v; version (VibeJsonFieldNames) { if (m_magic == 0x1337f00d) { foreach (idx, ref av; m_array) av.m_name = format("%s[%s]", m_name, idx); } else m_name = null; } return v; } /// ditto Json[string] opAssign(Json[string] v) { runDestructors(); m_type = Type.object; m_object = v; version (VibeJsonFieldNames) { if (m_magic == 0x1337f00d) { foreach (key, ref av; m_object) av.m_name = format("%s.%s", m_name, key); } else m_name = null; } return v; } /** Allows removal of values from Type.Object Json objects. */ void remove(string item) { checkType!(Json[string])(); m_object.remove(item); } /** The current type id of this JSON object. */ @property Type type() const @safe { return m_type; } /** Clones a JSON value recursively. */ Json clone() const { final switch (m_type) { case Type.undefined: return Json.undefined; case Type.null_: return Json(null); case Type.bool_: return Json(m_bool); case Type.int_: return Json(m_int); case Type.bigInt: return Json(m_bigInt); case Type.float_: return Json(m_float); case Type.string: return Json(m_string); case Type.array: auto ret = Json.emptyArray; foreach (v; this.byValue) ret ~= v.clone(); return ret; case Type.object: auto ret = Json.emptyObject; foreach (name, v; this.byKeyValue) ret[name] = v.clone(); return ret; } } /** Allows direct indexing of array typed JSON values. */ ref inout(Json) opIndex(size_t idx) inout { checkType!(Json[])(); return m_array[idx]; } /// unittest { Json value = Json.emptyArray; value ~= 1; value ~= true; value ~= "foo"; assert(value[0] == 1); assert(value[1] == true); assert(value[2] == "foo"); } /** Allows direct indexing of object typed JSON values using a string as the key. Returns an object of `Type.undefined` if the key was not found. */ const(Json) opIndex(string key) const { checkType!(Json[string])(); if( auto pv = key in m_object ) return *pv; Json ret = Json.undefined; ret.m_string = key; version (VibeJsonFieldNames) ret.m_name = format("%s.%s", m_name, key); return ret; } /// ditto ref Json opIndex(string key) { checkType!(Json[string])(); if( auto pv = key in m_object ) return *pv; if (m_object is null) { m_object = ["": Json.init]; m_object.remove(""); } m_object[key] = Json.init; assert(m_object !is null); assert(key in m_object, "Failed to insert key '"~key~"' into AA!?"); m_object[key].m_type = Type.undefined; // DMDBUG: AAs are teh $H1T!!!11 assert(m_object[key].type == Type.undefined); m_object[key].m_string = key; version (VibeJsonFieldNames) m_object[key].m_name = format("%s.%s", m_name, key); return m_object[key]; } /// unittest { Json value = Json.emptyObject; value["a"] = 1; value["b"] = true; value["c"] = "foo"; assert(value["a"] == 1); assert(value["b"] == true); assert(value["c"] == "foo"); assert(value["not-existing"].type() == Type.undefined); } /** Returns a slice of a JSON array. */ inout(Json[]) opSlice() inout { checkType!(Json[])(); return m_array; } /// inout(Json[]) opSlice(size_t from, size_t to) inout { checkType!(Json[])(); return m_array[from .. to]; } /** Returns the number of entries of string, array or object typed JSON values. */ @property size_t length() const @trusted { checkType!(string, Json[], Json[string])("property length"); switch(m_type){ case Type.string: return m_string.length; case Type.array: return m_array.length; case Type.object: return m_object.length; default: assert(false); } } /** Allows foreach iterating over JSON objects and arrays. */ int opApply(scope int delegate(ref Json obj) del) @system { checkType!(Json[], Json[string])("opApply"); if( m_type == Type.array ){ foreach( ref v; m_array ) if( auto ret = del(v) ) return ret; return 0; } else { foreach( ref v; m_object ) if( v.type != Type.undefined ) if( auto ret = del(v) ) return ret; return 0; } } /// ditto int opApply(scope int delegate(ref const Json obj) del) const @system { checkType!(Json[], Json[string])("opApply"); if( m_type == Type.array ){ foreach( ref v; m_array ) if( auto ret = del(v) ) return ret; return 0; } else { foreach( ref v; m_object ) if( v.type != Type.undefined ) if( auto ret = del(v) ) return ret; return 0; } } /// ditto int opApply(scope int delegate(ref size_t idx, ref Json obj) del) @system { checkType!(Json[])("opApply"); foreach( idx, ref v; m_array ) if( auto ret = del(idx, v) ) return ret; return 0; } /// ditto int opApply(scope int delegate(ref size_t idx, ref const Json obj) del) const @system { checkType!(Json[])("opApply"); foreach( idx, ref v; m_array ) if( auto ret = del(idx, v) ) return ret; return 0; } /// ditto int opApply(scope int delegate(ref string idx, ref Json obj) del) @system { checkType!(Json[string])("opApply"); foreach( idx, ref v; m_object ) if( v.type != Type.undefined ) if( auto ret = del(idx, v) ) return ret; return 0; } /// ditto int opApply(scope int delegate(ref string idx, ref const Json obj) del) const @system { checkType!(Json[string])("opApply"); foreach( idx, ref v; m_object ) if( v.type != Type.undefined ) if( auto ret = del(idx, v) ) return ret; return 0; } private alias KeyValue = Tuple!(string, "key", Json, "value"); /// Iterates over all key/value pairs of an object. @property auto byKeyValue() @trusted { checkType!(Json[string])("byKeyValue"); return m_object.byKeyValue.map!(kv => KeyValue(kv.key, kv.value)).trustedRange; } /// ditto @property auto byKeyValue() const @trusted { checkType!(Json[string])("byKeyValue"); return m_object.byKeyValue.map!(kv => const(KeyValue)(kv.key, kv.value)).trustedRange; } /// Iterates over all index/value pairs of an array. @property auto byIndexValue() { checkType!(Json[])("byIndexValue"); return zip(iota(0, m_array.length), m_array); } /// ditto @property auto byIndexValue() const { checkType!(Json[])("byIndexValue"); return zip(iota(0, m_array.length), m_array); } /// Iterates over all values of an object or array. @property auto byValue() @trusted { checkType!(Json[], Json[string])("byValue"); static struct Rng { private { bool isArray; Json[] array; typeof(Json.init.m_object.byValue) object; } bool empty() @trusted { if (isArray) return array.length == 0; else return object.empty; } auto front() @trusted { if (isArray) return array[0]; else return object.front; } void popFront() @trusted { if (isArray) array = array[1 .. $]; else object.popFront(); } } if (m_type == Type.array) return Rng(true, m_array); else return Rng(false, null, m_object.byValue); } /// ditto @property auto byValue() const @trusted { checkType!(Json[], Json[string])("byValue"); static struct Rng { @safe: private { bool isArray; const(Json)[] array; typeof(const(Json).init.m_object.byValue) object; } bool empty() @trusted { if (isArray) return array.length == 0; else return object.empty; } auto front() @trusted { if (isArray) return array[0]; else return object.front; } void popFront() @trusted { if (isArray) array = array[1 .. $]; else object.popFront(); } } if (m_type == Type.array) return Rng(true, m_array); else return Rng(false, null, m_object.byValue); } /** Converts the JSON value to the corresponding D type - types must match exactly. Available_Types: $(UL $(LI `bool` (`Type.bool_`)) $(LI `double` (`Type.float_`)) $(LI `float` (Converted from `double`)) $(LI `long` (`Type.int_`)) $(LI `ulong`, `int`, `uint`, `short`, `ushort`, `byte`, `ubyte` (Converted from `long`)) $(LI `string` (`Type.string`)) $(LI `Json[]` (`Type.array`)) $(LI `Json[string]` (`Type.object`)) ) See_Also: `opt`, `to`, `deserializeJson` */ inout(T) opCast(T)() inout { return get!T; } /// ditto @property inout(T) get(T)() inout @trusted { static if (!is(T : bool) && is(T : long)) checkType!(long, BigInt)(); else checkType!T(); static if (is(T == bool)) return m_bool; else static if (is(T == double)) return m_float; else static if (is(T == float)) return cast(T)m_float; else static if (is(T == string)) return m_string; else static if (is(T == Json[])) return m_array; else static if (is(T == Json[string])) return m_object; else static if (is(T == BigInt)) return m_type == Type.bigInt ? m_bigInt : BigInt(m_int); else static if (is(T : long)) { if (m_type == Type.bigInt) { enforceJson(m_bigInt <= T.max && m_bigInt >= T.min, "Integer conversion out of bounds error"); return cast(T)m_bigInt.toLong(); } else { enforceJson(m_int <= T.max && m_int >= T.min, "Integer conversion out of bounds error"); return cast(T)m_int; } } else static assert(0, "JSON can only be cast to (bool, long, std.bigint.BigInt, double, string, Json[] or Json[string]. Not "~T.stringof~"."); } /** Returns the native type for this JSON if it matches the current runtime type. If the runtime type does not match the given native type, the 'def' parameter is returned instead. See_Also: `get` */ @property const(T) opt(T)(const(T) def = T.init) const { if( typeId!T != m_type ) return def; return get!T; } /// ditto @property T opt(T)(T def = T.init) { if( typeId!T != m_type ) return def; return get!T; } /** Converts the JSON value to the corresponding D type - types are converted as necessary. Automatically performs conversions between strings and numbers. See `get` for the list of available types. For converting/deserializing JSON to complex data types see `deserializeJson`. See_Also: `get`, `deserializeJson` */ @property inout(T) to(T)() inout { static if( is(T == bool) ){ final switch( m_type ){ case Type.undefined: return false; case Type.null_: return false; case Type.bool_: return m_bool; case Type.int_: return m_int != 0; case Type.bigInt: return m_bigInt != 0; case Type.float_: return m_float != 0; case Type.string: return m_string.length > 0; case Type.array: return m_array.length > 0; case Type.object: return m_object.length > 0; } } else static if( is(T == double) ){ final switch( m_type ){ case Type.undefined: return T.init; case Type.null_: return 0; case Type.bool_: return m_bool ? 1 : 0; case Type.int_: return m_int; case Type.bigInt: return bigIntToLong(); case Type.float_: return m_float; case Type.string: return .to!double(cast(string)m_string); case Type.array: return double.init; case Type.object: return double.init; } } else static if( is(T == float) ){ final switch( m_type ){ case Type.undefined: return T.init; case Type.null_: return 0; case Type.bool_: return m_bool ? 1 : 0; case Type.int_: return m_int; case Type.bigInt: return bigIntToLong(); case Type.float_: return m_float; case Type.string: return .to!float(cast(string)m_string); case Type.array: return float.init; case Type.object: return float.init; } } else static if( is(T == long) ){ final switch( m_type ){ case Type.undefined: return 0; case Type.null_: return 0; case Type.bool_: return m_bool ? 1 : 0; case Type.int_: return m_int; case Type.bigInt: return cast(long)bigIntToLong(); case Type.float_: return cast(long)m_float; case Type.string: return .to!long(m_string); case Type.array: return 0; case Type.object: return 0; } } else static if( is(T : long) ){ final switch( m_type ){ case Type.undefined: return 0; case Type.null_: return 0; case Type.bool_: return m_bool ? 1 : 0; case Type.int_: return cast(T)m_int; case Type.bigInt: return cast(T)bigIntToLong(); case Type.float_: return cast(T)m_float; case Type.string: return cast(T).to!long(cast(string)m_string); case Type.array: return 0; case Type.object: return 0; } } else static if( is(T == string) ){ switch( m_type ){ default: return toString(); case Type.string: return m_string; } } else static if( is(T == Json[]) ){ switch( m_type ){ default: return Json([this]); case Type.array: return m_array; } } else static if( is(T == Json[string]) ){ switch( m_type ){ default: return Json(["value": this]); case Type.object: return m_object; } } else static if( is(T == BigInt) ){ final switch( m_type ){ case Type.undefined: return BigInt(0); case Type.null_: return BigInt(0); case Type.bool_: return BigInt(m_bool ? 1 : 0); case Type.int_: return BigInt(m_int); case Type.bigInt: return m_bigInt; case Type.float_: return BigInt(cast(long)m_float); case Type.string: return BigInt(.to!long(m_string)); case Type.array: return BigInt(0); case Type.object: return BigInt(0); } } else static assert(0, "JSON can only be cast to (bool, long, std.bigint.BigInt, double, string, Json[] or Json[string]. Not "~T.stringof~"."); } /** Performs unary operations on the JSON value. The following operations are supported for each type: $(DL $(DT Null) $(DD none) $(DT Bool) $(DD ~) $(DT Int) $(DD +, -, ++, --) $(DT Float) $(DD +, -, ++, --) $(DT String) $(DD none) $(DT Array) $(DD none) $(DT Object) $(DD none) ) */ Json opUnary(string op)() const { static if( op == "~" ){ checkType!bool(); return Json(~m_bool); } else static if( op == "+" || op == "-" || op == "++" || op == "--" ){ checkType!(BigInt, long, double)("unary "~op); if( m_type == Type.int_ ) mixin("return Json("~op~"m_int);"); else if( m_type == Type.bigInt ) mixin("return Json("~op~"m_bigInt);"); else if( m_type == Type.float_ ) mixin("return Json("~op~"m_float);"); else assert(false); } else static assert(0, "Unsupported operator '"~op~"' for type JSON."); } /** Performs binary operations between JSON values. The two JSON values must be of the same run time type or a JSONException will be thrown. Only the operations listed are allowed for each of the types. $(DL $(DT Null) $(DD none) $(DT Bool) $(DD &&, ||) $(DT Int) $(DD +, -, *, /, %) $(DT Float) $(DD +, -, *, /, %) $(DT String) $(DD ~) $(DT Array) $(DD ~) $(DT Object) $(DD in) ) */ Json opBinary(string op)(ref const(Json) other) const { enforceJson(m_type == other.m_type, "Binary operation '"~op~"' between "~.to!string(m_type)~" and "~.to!string(other.m_type)~" JSON objects."); static if( op == "&&" ){ checkType!(bool)(op); return Json(m_bool && other.m_bool); } else static if( op == "||" ){ checkType!(bool)(op); return Json(m_bool || other.m_bool); } else static if( op == "+" ){ checkType!(BigInt, long, double)(op); if( m_type == Type.int_ ) return Json(m_int + other.m_int); else if( m_type == Type.bigInt ) return Json(() @trusted { return m_bigInt + other.m_bigInt; } ()); else if( m_type == Type.float_ ) return Json(m_float + other.m_float); else assert(false); } else static if( op == "-" ){ checkType!(BigInt, long, double)(op); if( m_type == Type.int_ ) return Json(m_int - other.m_int); else if( m_type == Type.bigInt ) return Json(() @trusted { return m_bigInt - other.m_bigInt; } ()); else if( m_type == Type.float_ ) return Json(m_float - other.m_float); else assert(false); } else static if( op == "*" ){ checkType!(BigInt, long, double)(op); if( m_type == Type.int_ ) return Json(m_int * other.m_int); else if( m_type == Type.bigInt ) return Json(() @trusted { return m_bigInt * other.m_bigInt; } ()); else if( m_type == Type.float_ ) return Json(m_float * other.m_float); else assert(false); } else static if( op == "/" ){ checkType!(BigInt, long, double)(op); if( m_type == Type.int_ ) return Json(m_int / other.m_int); else if( m_type == Type.bigInt ) return Json(() @trusted { return m_bigInt / other.m_bigInt; } ()); else if( m_type == Type.float_ ) return Json(m_float / other.m_float); else assert(false); } else static if( op == "%" ){ checkType!(BigInt, long, double)(op); if( m_type == Type.int_ ) return Json(m_int % other.m_int); else if( m_type == Type.bigInt ) return Json(() @trusted { return m_bigInt % other.m_bigInt; } ()); else if( m_type == Type.float_ ) return Json(m_float % other.m_float); else assert(false); } else static if( op == "~" ){ checkType!(string, Json[])(op); if( m_type == Type.string ) return Json(m_string ~ other.m_string); else if (m_type == Type.array) return Json(m_array ~ other.m_array); else assert(false); } else static assert(0, "Unsupported operator '"~op~"' for type JSON."); } /// ditto Json opBinary(string op)(Json other) if( op == "~" ) { static if( op == "~" ){ checkType!(string, Json[])(op); if( m_type == Type.string ) return Json(m_string ~ other.m_string); else if( m_type == Type.array ) return Json(m_array ~ other.m_array); else assert(false); } else static assert(0, "Unsupported operator '"~op~"' for type JSON."); } /// ditto void opOpAssign(string op)(Json other) if (op == "+" || op == "-" || op == "*" || op == "/" || op == "%" || op =="~") { enforceJson(m_type == other.m_type || op == "~" && m_type == Type.array, "Binary operation '"~op~"=' between "~.to!string(m_type)~" and "~.to!string(other.m_type)~" JSON objects."); static if( op == "+" ){ if( m_type == Type.int_ ) m_int += other.m_int; else if( m_type == Type.bigInt ) m_bigInt += other.m_bigInt; else if( m_type == Type.float_ ) m_float += other.m_float; else enforceJson(false, "'+=' only allowed for scalar types, not "~.to!string(m_type)~"."); } else static if( op == "-" ){ if( m_type == Type.int_ ) m_int -= other.m_int; else if( m_type == Type.bigInt ) m_bigInt -= other.m_bigInt; else if( m_type == Type.float_ ) m_float -= other.m_float; else enforceJson(false, "'-=' only allowed for scalar types, not "~.to!string(m_type)~"."); } else static if( op == "*" ){ if( m_type == Type.int_ ) m_int *= other.m_int; else if( m_type == Type.bigInt ) m_bigInt *= other.m_bigInt; else if( m_type == Type.float_ ) m_float *= other.m_float; else enforceJson(false, "'*=' only allowed for scalar types, not "~.to!string(m_type)~"."); } else static if( op == "/" ){ if( m_type == Type.int_ ) m_int /= other.m_int; else if( m_type == Type.bigInt ) m_bigInt /= other.m_bigInt; else if( m_type == Type.float_ ) m_float /= other.m_float; else enforceJson(false, "'/=' only allowed for scalar types, not "~.to!string(m_type)~"."); } else static if( op == "%" ){ if( m_type == Type.int_ ) m_int %= other.m_int; else if( m_type == Type.bigInt ) m_bigInt %= other.m_bigInt; else if( m_type == Type.float_ ) m_float %= other.m_float; else enforceJson(false, "'%=' only allowed for scalar types, not "~.to!string(m_type)~"."); } else static if( op == "~" ){ if (m_type == Type.string) m_string ~= other.m_string; else if (m_type == Type.array) { if (other.m_type == Type.array) m_array ~= other.m_array; else appendArrayElement(other); } else enforceJson(false, "'~=' only allowed for string and array types, not "~.to!string(m_type)~"."); } else static assert(0, "Unsupported operator '"~op~"=' for type JSON."); } /// ditto void opOpAssign(string op, T)(T other) if (!is(T == Json) && is(typeof(Json(other)))) { opOpAssign!op(Json(other)); } /// ditto Json opBinary(string op)(bool other) const { checkType!bool(); mixin("return Json(m_bool "~op~" other);"); } /// ditto Json opBinary(string op)(long other) const { checkType!(long, BigInt)(); if (m_type == Type.bigInt) mixin("return Json(m_bigInt "~op~" other);"); else mixin("return Json(m_int "~op~" other);"); } /// ditto Json opBinary(string op)(BigInt other) const { checkType!(long, BigInt)(); if (m_type == Type.bigInt) mixin("return Json(m_bigInt "~op~" other);"); else mixin("return Json(m_int "~op~" other);"); } /// ditto Json opBinary(string op)(double other) const { checkType!double(); mixin("return Json(m_float "~op~" other);"); } /// ditto Json opBinary(string op)(string other) const { checkType!string(); mixin("return Json(m_string "~op~" other);"); } /// ditto Json opBinary(string op)(Json[] other) { checkType!(Json[])(); mixin("return Json(m_array "~op~" other);"); } /// ditto Json opBinaryRight(string op)(bool other) const { checkType!bool(); mixin("return Json(other "~op~" m_bool);"); } /// ditto Json opBinaryRight(string op)(long other) const { checkType!(long, BigInt)(); if (m_type == Type.bigInt) mixin("return Json(other "~op~" m_bigInt);"); else mixin("return Json(other "~op~" m_int);"); } /// ditto Json opBinaryRight(string op)(BigInt other) const { checkType!(long, BigInt)(); if (m_type == Type.bigInt) mixin("return Json(other "~op~" m_bigInt);"); else mixin("return Json(other "~op~" m_int);"); } /// ditto Json opBinaryRight(string op)(double other) const { checkType!double(); mixin("return Json(other "~op~" m_float);"); } /// ditto Json opBinaryRight(string op)(string other) const if(op == "~") { checkType!string(); return Json(other ~ m_string); } /// ditto Json opBinaryRight(string op)(Json[] other) { checkType!(Json[])(); mixin("return Json(other "~op~" m_array);"); } /** Checks wheter a particular key is set and returns a pointer to it. For field that don't exist or have a type of `Type.undefined`, the `in` operator will return `null`. */ inout(Json)* opBinaryRight(string op)(string other) inout if(op == "in") { checkType!(Json[string])(); auto pv = other in m_object; if (!pv) return null; if (pv.type == Type.undefined) return null; return pv; } /// unittest { auto j = Json.emptyObject; j["a"] = "foo"; j["b"] = Json.undefined; assert("a" in j); assert(("a" in j).get!string == "foo"); assert("b" !in j); assert("c" !in j); } /** * The append operator will append arrays. This method always appends it's argument as an array element, so nested arrays can be created. */ void appendArrayElement(Json element) { enforceJson(m_type == Type.array, "'appendArrayElement' only allowed for array types, not "~.to!string(m_type)~"."); m_array ~= element; } /** Compares two JSON values for equality. If the two values have different types, they are considered unequal. This differs with ECMA script, which performs a type conversion before comparing the values. */ bool opEquals(ref const Json other) const { if( m_type != other.m_type ) return false; final switch(m_type){ case Type.undefined: return false; case Type.null_: return true; case Type.bool_: return m_bool == other.m_bool; case Type.int_: return m_int == other.m_int; case Type.bigInt: return m_bigInt == other.m_bigInt; case Type.float_: return m_float == other.m_float; case Type.string: return m_string == other.m_string; case Type.array: return m_array == other.m_array; case Type.object: return m_object == other.m_object; } } /// ditto bool opEquals(const Json other) const { return opEquals(other); } /// ditto bool opEquals(typeof(null)) const { return m_type == Type.null_; } /// ditto bool opEquals(bool v) const { return m_type == Type.bool_ && m_bool == v; } /// ditto bool opEquals(int v) const { return (m_type == Type.int_ && m_int == v) || (m_type == Type.bigInt && m_bigInt == v); } /// ditto bool opEquals(long v) const { return (m_type == Type.int_ && m_int == v) || (m_type == Type.bigInt && m_bigInt == v); } /// ditto bool opEquals(BigInt v) const { return (m_type == Type.int_ && m_int == v) || (m_type == Type.bigInt && m_bigInt == v); } /// ditto bool opEquals(double v) const { return m_type == Type.float_ && m_float == v; } /// ditto bool opEquals(string v) const { return m_type == Type.string && m_string == v; } /** Compares two JSON values. If the types of the two values differ, the value with the smaller type id is considered the smaller value. This differs from ECMA script, which performs a type conversion before comparing the values. JSON values of type Object cannot be compared and will throw an exception. */ int opCmp(ref const Json other) const { if( m_type != other.m_type ) return m_type < other.m_type ? -1 : 1; final switch(m_type){ case Type.undefined: return 0; case Type.null_: return 0; case Type.bool_: return m_bool < other.m_bool ? -1 : m_bool == other.m_bool ? 0 : 1; case Type.int_: return m_int < other.m_int ? -1 : m_int == other.m_int ? 0 : 1; case Type.bigInt: return () @trusted { return m_bigInt < other.m_bigInt; } () ? -1 : m_bigInt == other.m_bigInt ? 0 : 1; case Type.float_: return m_float < other.m_float ? -1 : m_float == other.m_float ? 0 : 1; case Type.string: return m_string < other.m_string ? -1 : m_string == other.m_string ? 0 : 1; case Type.array: return m_array < other.m_array ? -1 : m_array == other.m_array ? 0 : 1; case Type.object: enforceJson(false, "JSON objects cannot be compared."); assert(false); } } alias opDollar = length; /** Returns the type id corresponding to the given D type. */ static @property Type typeId(T)() { static if( is(T == typeof(null)) ) return Type.null_; else static if( is(T == bool) ) return Type.bool_; else static if( is(T == double) ) return Type.float_; else static if( is(T == float) ) return Type.float_; else static if( is(T : long) ) return Type.int_; else static if( is(T == string) ) return Type.string; else static if( is(T == Json[]) ) return Type.array; else static if( is(T == Json[string]) ) return Type.object; else static if( is(T == BigInt) ) return Type.bigInt; else static assert(false, "Unsupported JSON type '"~T.stringof~"'. Only bool, long, std.bigint.BigInt, double, string, Json[] and Json[string] are allowed."); } /** Returns the JSON object as a string. For large JSON values use writeJsonString instead as this function will store the whole string in memory, whereas writeJsonString writes it out bit for bit. See_Also: writeJsonString, toPrettyString */ string toString() const @trusted { // DMD BUG: this should actually be all @safe, but for some reason // @safe inference for writeJsonString doesn't work. auto ret = appender!string(); writeJsonString(ret, this); return ret.data; } /// ditto void toString(scope void delegate(const(char)[]) @safe sink, FormatSpec!char fmt) @trusted { // DMD BUG: this should actually be all @safe, but for some reason // @safe inference for writeJsonString doesn't work. static struct DummyRangeS { void delegate(const(char)[]) @safe sink; void put(const(char)[] str) @safe { sink(str); } void put(char ch) @trusted { sink((&ch)[0 .. 1]); } } auto r = DummyRangeS(sink); writeJsonString(r, this); } /// ditto void toString(scope void delegate(const(char)[]) @system sink, FormatSpec!char fmt) @system { // DMD BUG: this should actually be all @safe, but for some reason // @safe inference for writeJsonString doesn't work. static struct DummyRange { void delegate(const(char)[]) sink; @trusted: void put(const(char)[] str) { sink(str); } void put(char ch) { sink((&ch)[0 .. 1]); } } auto r = DummyRange(sink); writeJsonString(r, this); } /** Returns the JSON object as a "pretty" string. --- auto json = Json(["foo": Json("bar")]); writeln(json.toPrettyString()); // output: // { // "foo": "bar" // } --- Params: level = Specifies the base amount of indentation for the output. Indentation is always done using tab characters. See_Also: writePrettyJsonString, toString */ string toPrettyString(int level = 0) const @trusted { auto ret = appender!string(); writePrettyJsonString(ret, this, level); return ret.data; } private void checkType(TYPES...)(string op = null) const { bool matched = false; foreach (T; TYPES) if (m_type == typeId!T) matched = true; if (matched) return; string name; version (VibeJsonFieldNames) { if (m_name.length) name = m_name ~ " of type " ~ m_type.to!string; else name = "JSON of type " ~ m_type.to!string; } else name = "JSON of type " ~ m_type.to!string; string expected; static if (TYPES.length == 1) expected = typeId!(TYPES[0]).to!string; else { foreach (T; TYPES) { if (expected.length > 0) expected ~= ", "; expected ~= typeId!T.to!string; } } if (!op.length) throw new JSONException(format("Got %s, expected %s.", name, expected)); else throw new JSONException(format("Got %s, expected %s for %s.", name, expected, op)); } private void initBigInt() @trusted { BigInt[1] init_; // BigInt is a struct, and it has a special BigInt.init value, which differs from null. // m_data has no special initializer and when it tries to first access to BigInt // via m_bigInt(), we should explicitly initialize m_data with BigInt.init m_data[0 .. BigInt.sizeof] = cast(void[])init_; } private void runDestructors() { if (m_type != Type.bigInt) return; BigInt init_; // After swaping, init_ contains the real number from Json, and it // will be destroyed when this function is finished. // m_bigInt now contains static BigInt.init value and destruction may // be ommited for it. swap(init_, m_bigInt); } private long bigIntToLong() inout { assert(m_type == Type.bigInt, format("Converting non-bigInt type with bitIntToLong!?: %s", cast(Type)m_type)); enforceJson(m_bigInt >= long.min && m_bigInt <= long.max, "Number out of range while converting BigInt("~format("%d", m_bigInt)~") to long."); return m_bigInt.toLong(); } /*invariant() { assert(m_type >= Type.Undefined && m_type <= Type.Object); }*/ } @safe unittest { // issue #1234 - @safe toString auto j = Json(true); j.toString((str) @safe {}, FormatSpec!char("s")); assert(j.toString() == "true"); } /******************************************************************************/ /* public functions */ /******************************************************************************/ /** Parses the given range as a JSON string and returns the corresponding Json object. The range is shrunk during parsing, leaving any remaining text that is not part of the JSON contents. Throws a JSONException if any parsing error occured. */ Json parseJson(R)(ref R range, int* line = null, string filename = null) if( is(R == string) ) { Json ret; enforceJson(!range.empty, "JSON string is empty.", filename, 0); skipWhitespace(range, line); enforceJson(!range.empty, "JSON string contains only whitespaces.", filename, 0); version(JsonLineNumbers) { int curline = line ? *line : 0; } bool minus = false; switch( range.front ){ case 'f': enforceJson(range[1 .. $].startsWith("alse"), "Expected 'false', got '"~range[0 .. min(5, $)]~"'.", filename, line); range.popFrontN(5); ret = false; break; case 'n': enforceJson(range[1 .. $].startsWith("ull"), "Expected 'null', got '"~range[0 .. min(4, $)]~"'.", filename, line); range.popFrontN(4); ret = null; break; case 't': enforceJson(range[1 .. $].startsWith("rue"), "Expected 'true', got '"~range[0 .. min(4, $)]~"'.", filename, line); range.popFrontN(4); ret = true; break; case '-': case '0': .. case '9': bool is_long_overflow; bool is_float; auto num = skipNumber(range, is_float, is_long_overflow); if( is_float ) { ret = to!double(num); } else if (is_long_overflow) { ret = () @trusted { return BigInt(num.to!string); } (); } else { ret = to!long(num); } break; case '\"': ret = skipJsonString(range); break; case '[': auto arr = appender!(Json[]); range.popFront(); while (true) { skipWhitespace(range, line); enforceJson(!range.empty, "Missing ']' before EOF.", filename, line); if(range.front == ']') break; arr ~= parseJson(range, line, filename); skipWhitespace(range, line); enforceJson(!range.empty, "Missing ']' before EOF.", filename, line); enforceJson(range.front == ',' || range.front == ']', format("Expected ']' or ',' - got '%s'.", range.front), filename, line); if( range.front == ']' ) break; else range.popFront(); } range.popFront(); ret = arr.data; break; case '{': Json[string] obj; range.popFront(); while (true) { skipWhitespace(range, line); enforceJson(!range.empty, "Missing '}' before EOF.", filename, line); if(range.front == '}') break; string key = skipJsonString(range); skipWhitespace(range, line); enforceJson(range.startsWith(":"), "Expected ':' for key '" ~ key ~ "'", filename, line); range.popFront(); skipWhitespace(range, line); Json itm = parseJson(range, line, filename); obj[key] = itm; skipWhitespace(range, line); enforceJson(!range.empty, "Missing '}' before EOF.", filename, line); enforceJson(range.front == ',' || range.front == '}', format("Expected '}' or ',' - got '%s'.", range.front), filename, line); if (range.front == '}') break; else range.popFront(); } range.popFront(); ret = obj; break; default: enforceJson(false, format("Expected valid JSON token, got '%s'.", range[0 .. min(12, $)]), filename, line); assert(false); } assert(ret.type != Json.Type.undefined); version(JsonLineNumbers) ret.line = curline; return ret; } /** Parses the given JSON string and returns the corresponding Json object. Throws a JSONException if any parsing error occurs. */ Json parseJsonString(string str, string filename = null) @safe { auto strcopy = str; int line = 0; auto ret = parseJson(strcopy, () @trusted { return &line; } (), filename); enforceJson(strcopy.strip().length == 0, "Expected end of string after JSON value.", filename, line); return ret; } @safe unittest { // These currently don't work at compile time assert(parseJsonString("17559991181826658461") == Json(BigInt(17559991181826658461UL))); assert(parseJsonString("99999999999999999999999999") == () @trusted { return Json(BigInt("99999999999999999999999999")); } ()); auto json = parseJsonString(`{"hey": "This is @à test éhééhhéhéé !%/??*&?\ud83d\udcec"}`); assert(json.toPrettyString() == parseJsonString(json.toPrettyString()).toPrettyString()); bool test() { assert(parseJsonString("null") == Json(null)); assert(parseJsonString("true") == Json(true)); assert(parseJsonString("false") == Json(false)); assert(parseJsonString("1") == Json(1)); assert(parseJsonString("2.0") == Json(2.0)); assert(parseJsonString("\"test\"") == Json("test")); assert(parseJsonString("[1, 2, 3]") == Json([Json(1), Json(2), Json(3)])); assert(parseJsonString("{\"a\": 1}") == Json(["a": Json(1)])); assert(parseJsonString(`"\\\/\b\f\n\r\t\u1234"`).get!string == "\\/\b\f\n\r\t\u1234"); return true; } // Run at compile time and runtime assert(test()); static assert(test()); } @safe unittest { bool test() { try parseJsonString(" \t\n "); catch (Exception e) assert(e.msg.endsWith("JSON string contains only whitespaces.")); try parseJsonString(`{"a": 1`); catch (Exception e) assert(e.msg.endsWith("Missing '}' before EOF.")); try parseJsonString(`{"a": 1 x`); catch (Exception e) assert(e.msg.endsWith("Expected '}' or ',' - got 'x'.")); try parseJsonString(`[1`); catch (Exception e) assert(e.msg.endsWith("Missing ']' before EOF.")); try parseJsonString(`[1 x`); catch (Exception e) assert(e.msg.endsWith("Expected ']' or ',' - got 'x'.")); return true; } // Run at compile time and runtime assert(test()); static assert(test()); } /** Serializes the given value to JSON. The following types of values are supported: $(DL $(DT `Json`) $(DD Used as-is) $(DT `null`) $(DD Converted to `Json.Type.null_`) $(DT `bool`) $(DD Converted to `Json.Type.bool_`) $(DT `float`, `double`) $(DD Converted to `Json.Type.float_`) $(DT `short`, `ushort`, `int`, `uint`, `long`, `ulong`) $(DD Converted to `Json.Type.int_`) $(DT `BigInt`) $(DD Converted to `Json.Type.bigInt`) $(DT `string`) $(DD Converted to `Json.Type.string`) $(DT `T[]`) $(DD Converted to `Json.Type.array`) $(DT `T[string]`) $(DD Converted to `Json.Type.object`) $(DT `struct`) $(DD Converted to `Json.Type.object`) $(DT `class`) $(DD Converted to `Json.Type.object` or `Json.Type.null_`) ) All entries of an array or an associative array, as well as all R/W properties and all public fields of a struct/class are recursively serialized using the same rules. Fields ending with an underscore will have the last underscore stripped in the serialized output. This makes it possible to use fields with D keywords as their name by simply appending an underscore. The following methods can be used to customize the serialization of structs/classes: --- Json toJson() const; static T fromJson(Json src); string toString() const; static T fromString(string src); --- The methods will have to be defined in pairs. The first pair that is implemented by the type will be used for serialization (i.e. `toJson` overrides `toString`). See_Also: `deserializeJson`, `vibe.data.serialization` */ Json serializeToJson(T)(T value) { return serialize!JsonSerializer(value); } /// ditto void serializeToJson(R, T)(R destination, T value) if (isOutputRange!(R, char) || isOutputRange!(R, ubyte)) { serialize!(JsonStringSerializer!R)(value, destination); } /// ditto string serializeToJsonString(T)(T value) { auto ret = appender!string; serializeToJson(ret, value); return ret.data; } /// @safe unittest { struct Foo { int number; string str; } Foo f; f.number = 12; f.str = "hello"; string json = serializeToJsonString(f); assert(json == `{"number":12,"str":"hello"}`); Json jsonval = serializeToJson(f); assert(jsonval.type == Json.Type.object); assert(jsonval["number"] == Json(12)); assert(jsonval["str"] == Json("hello")); } /** Serializes the given value to a pretty printed JSON string. See_also: `serializeToJson`, `vibe.data.serialization` */ void serializeToPrettyJson(R, T)(R destination, T value) if (isOutputRange!(R, char) || isOutputRange!(R, ubyte)) { serialize!(JsonStringSerializer!(R, true))(value, destination); } /// ditto string serializeToPrettyJson(T)(T value) { auto ret = appender!string; serializeToPrettyJson(ret, value); return ret.data; } /// @safe unittest { struct Foo { int number; string str; } Foo f; f.number = 12; f.str = "hello"; string json = serializeToPrettyJson(f); assert(json == `{ "number": 12, "str": "hello" }`); } /** Deserializes a JSON value into the destination variable. The same types as for `serializeToJson()` are supported and handled inversely. See_Also: `serializeToJson`, `serializeToJsonString`, `vibe.data.serialization` */ void deserializeJson(T)(ref T dst, Json src) { dst = deserializeJson!T(src); } /// ditto T deserializeJson(T)(Json src) { return deserialize!(JsonSerializer, T)(src); } /// ditto T deserializeJson(T, R)(R input) if (!is(R == Json) && isInputRange!R) { return deserialize!(JsonStringSerializer!R, T)(input); } /// @safe unittest { struct Foo { int number; string str; } Foo f = deserializeJson!Foo(`{"number": 12, "str": "hello"}`); assert(f.number == 12); assert(f.str == "hello"); } @safe unittest { import std.stdio; enum Foo : string { k = "test" } enum Boo : int { l = 5 } static struct S { float a; double b; bool c; int d; string e; byte f; ubyte g; long h; ulong i; float[] j; Foo k; Boo l; } immutable S t = {1.5, -3.0, true, int.min, "Test", -128, 255, long.min, ulong.max, [1.1, 1.2, 1.3], Foo.k, Boo.l}; S u; deserializeJson(u, serializeToJson(t)); assert(t.a == u.a); assert(t.b == u.b); assert(t.c == u.c); assert(t.d == u.d); assert(t.e == u.e); assert(t.f == u.f); assert(t.g == u.g); assert(t.h == u.h); assert(t.i == u.i); assert(t.j == u.j); assert(t.k == u.k); assert(t.l == u.l); } @safe unittest { assert(uint.max == serializeToJson(uint.max).deserializeJson!uint); assert(ulong.max == serializeToJson(ulong.max).deserializeJson!ulong); } unittest { static struct A { int value; static A fromJson(Json val) @safe { return A(val.get!int); } Json toJson() const @safe { return Json(value); } } static struct C { int value; static C fromString(string val) @safe { return C(val.to!int); } string toString() const @safe { return value.to!string; } } static struct D { int value; } assert(serializeToJson(const A(123)) == Json(123)); assert(serializeToJson(A(123)) == Json(123)); assert(serializeToJson(const C(123)) == Json("123")); assert(serializeToJson(C(123)) == Json("123")); assert(serializeToJson(const D(123)) == serializeToJson(["value": 123])); assert(serializeToJson(D(123)) == serializeToJson(["value": 123])); } unittest { auto d = Date(2001,1,1); deserializeJson(d, serializeToJson(Date.init)); assert(d == Date.init); deserializeJson(d, serializeToJson(Date(2001,1,1))); assert(d == Date(2001,1,1)); struct S { immutable(int)[] x; } S s; deserializeJson(s, serializeToJson(S([1,2,3]))); assert(s == S([1,2,3])); struct T { @optional S s; @optional int i; @optional float f_; // underscore strip feature @optional double d; @optional string str; } auto t = T(S([1,2,3])); deserializeJson(t, parseJsonString(`{ "s" : null, "i" : null, "f" : null, "d" : null, "str" : null }`)); assert(text(t) == text(T())); } unittest { static class C { @safe: int a; private int _b; @property int b() const { return _b; } @property void b(int v) { _b = v; } @property int test() const { return 10; } void test2() {} } C c = new C; c.a = 1; c.b = 2; C d; deserializeJson(d, serializeToJson(c)); assert(c.a == d.a); assert(c.b == d.b); } unittest { static struct C { @safe: int value; static C fromString(string val) { return C(val.to!int); } string toString() const { return value.to!string; } } enum Color { Red, Green, Blue } { static class T { @safe: string[Color] enumIndexedMap; string[C] stringableIndexedMap; this() { enumIndexedMap = [ Color.Red : "magenta", Color.Blue : "deep blue" ]; stringableIndexedMap = [ C(42) : "forty-two" ]; } } T original = new T; original.enumIndexedMap[Color.Green] = "olive"; T other; deserializeJson(other, serializeToJson(original)); assert(serializeToJson(other) == serializeToJson(original)); } { static struct S { string[Color] enumIndexedMap; string[C] stringableIndexedMap; } S *original = new S; original.enumIndexedMap = [ Color.Red : "magenta", Color.Blue : "deep blue" ]; original.enumIndexedMap[Color.Green] = "olive"; original.stringableIndexedMap = [ C(42) : "forty-two" ]; S other; deserializeJson(other, serializeToJson(original)); assert(serializeToJson(other) == serializeToJson(original)); } } unittest { import std.typecons : Nullable; struct S { Nullable!int a, b; } S s; s.a = 2; auto j = serializeToJson(s); assert(j["a"].type == Json.Type.int_); assert(j["b"].type == Json.Type.null_); auto t = deserializeJson!S(j); assert(!t.a.isNull() && t.a == 2); assert(t.b.isNull()); } unittest { // #840 int[2][2] nestedArray = 1; assert(nestedArray.serializeToJson.deserializeJson!(typeof(nestedArray)) == nestedArray); } unittest { // #1109 static class C { @safe: int mem; this(int m) { mem = m; } static C fromJson(Json j) { return new C(j.get!int-1); } Json toJson() const { return Json(mem+1); } } const c = new C(13); assert(serializeToJson(c) == Json(14)); assert(deserializeJson!C(Json(14)).mem == 13); } unittest { // const and mutable json Json j = Json(1); const k = Json(2); assert(serializeToJson(j) == Json(1)); assert(serializeToJson(k) == Json(2)); } unittest { // issue #1660 - deserialize AA whose key type is string-based enum enum Foo: string { Bar = "bar", Buzz = "buzz" } struct S { int[Foo] f; } const s = S([Foo.Bar: 2000]); assert(serializeToJson(s)["f"] == Json([Foo.Bar: Json(2000)])); auto j = Json.emptyObject; j["f"] = [Foo.Bar: Json(2000)]; assert(deserializeJson!S(j).f == [Foo.Bar: 2000]); } /** Serializer for a plain Json representation. See_Also: vibe.data.serialization.serialize, vibe.data.serialization.deserialize, serializeToJson, deserializeJson */ struct JsonSerializer { template isJsonBasicType(T) { enum isJsonBasicType = std.traits.isNumeric!T || isBoolean!T || is(T == string) || is(T == typeof(null)) || isJsonSerializable!T; } template isSupportedValueType(T) { enum isSupportedValueType = isJsonBasicType!T || is(T == Json); } private { Json m_current; Json[] m_compositeStack; } this(Json data) @safe { m_current = data; } @disable this(this); // // serialization // Json getSerializedResult() @safe { return m_current; } void beginWriteDictionary(Traits)() { m_compositeStack ~= Json.emptyObject; } void endWriteDictionary(Traits)() { m_current = m_compositeStack[$-1]; m_compositeStack.length--; } void beginWriteDictionaryEntry(Traits)(string name) {} void endWriteDictionaryEntry(Traits)(string name) { m_compositeStack[$-1][name] = m_current; } void beginWriteArray(Traits)(size_t) { m_compositeStack ~= Json.emptyArray; } void endWriteArray(Traits)() { m_current = m_compositeStack[$-1]; m_compositeStack.length--; } void beginWriteArrayEntry(Traits)(size_t) {} void endWriteArrayEntry(Traits)(size_t) { m_compositeStack[$-1].appendArrayElement(m_current); } void writeValue(Traits, T)(in T value) if (!is(T == Json)) { static if (isJsonSerializable!T) { static if (!__traits(compiles, () @safe { return value.toJson(); } ())) pragma(msg, "Non-@safe toJson/fromJson methods are deprecated - annotate "~T.stringof~".toJson() with @safe."); m_current = () @trusted { return value.toJson(); } (); } else m_current = Json(value); } void writeValue(Traits, T)(Json value) if (is(T == Json)) { m_current = value; } void writeValue(Traits, T)(in Json value) if (is(T == Json)) { m_current = value.clone; } // // deserialization // void readDictionary(Traits)(scope void delegate(string) @safe field_handler) { enforceJson(m_current.type == Json.Type.object, "Expected JSON object, got "~m_current.type.to!string); auto old = m_current; foreach (string key, value; m_current.get!(Json[string])) { m_current = value; field_handler(key); } m_current = old; } void beginReadDictionaryEntry(Traits)(string name) {} void endReadDictionaryEntry(Traits)(string name) {} void readArray(Traits)(scope void delegate(size_t) @safe size_callback, scope void delegate() @safe entry_callback) { enforceJson(m_current.type == Json.Type.array, "Expected JSON array, got "~m_current.type.to!string); auto old = m_current; size_callback(m_current.length); foreach (ent; old.get!(Json[])) { m_current = ent; entry_callback(); } m_current = old; } void beginReadArrayEntry(Traits)(size_t index) {} void endReadArrayEntry(Traits)(size_t index) {} T readValue(Traits, T)() @safe { static if (is(T == Json)) return m_current; else static if (isJsonSerializable!T) { static if (!__traits(compiles, () @safe { return T.fromJson(m_current); } ())) pragma(msg, "Non-@safe toJson/fromJson methods are deprecated - annotate "~T.stringof~".fromJson() with @safe."); return () @trusted { return T.fromJson(m_current); } (); } else static if (is(T == float) || is(T == double)) { switch (m_current.type) { default: return cast(T)m_current.get!long; case Json.Type.null_: goto case; case Json.Type.undefined: return T.nan; case Json.Type.float_: return cast(T)m_current.get!double; case Json.Type.bigInt: return cast(T)m_current.bigIntToLong(); } } else { return m_current.get!T(); } } bool tryReadNull(Traits)() { return m_current.type == Json.Type.null_; } } /** Serializer for a range based plain JSON string representation. See_Also: vibe.data.serialization.serialize, vibe.data.serialization.deserialize, serializeToJson, deserializeJson */ struct JsonStringSerializer(R, bool pretty = false) if (isInputRange!R || isOutputRange!(R, char)) { private { R m_range; size_t m_level = 0; } template isJsonBasicType(T) { enum isJsonBasicType = std.traits.isNumeric!T || isBoolean!T || is(T == string) || is(T == typeof(null)) || isJsonSerializable!T; } template isSupportedValueType(T) { enum isSupportedValueType = isJsonBasicType!T || is(T == Json); } this(R range) { m_range = range; } @disable this(this); // // serialization // static if (isOutputRange!(R, char)) { private { bool m_firstInComposite; } void getSerializedResult() {} void beginWriteDictionary(Traits)() { startComposite(); m_range.put('{'); } void endWriteDictionary(Traits)() { endComposite(); m_range.put("}"); } void beginWriteDictionaryEntry(Traits)(string name) { startCompositeEntry(); m_range.put('"'); m_range.jsonEscape(name); static if (pretty) m_range.put(`": `); else m_range.put(`":`); } void endWriteDictionaryEntry(Traits)(string name) {} void beginWriteArray(Traits)(size_t) { startComposite(); m_range.put('['); } void endWriteArray(Traits)() { endComposite(); m_range.put(']'); } void beginWriteArrayEntry(Traits)(size_t) { startCompositeEntry(); } void endWriteArrayEntry(Traits)(size_t) {} void writeValue(Traits, T)(in T value) { static if (is(T == typeof(null))) m_range.put("null"); else static if (is(T == bool)) m_range.put(value ? "true" : "false"); else static if (is(T : long)) m_range.formattedWrite("%s", value); else static if (is(T == BigInt)) () @trusted { m_range.formattedWrite("%d", value); } (); else static if (is(T : real)) value == value ? m_range.formattedWrite("%.16g", value) : m_range.put("null"); else static if (is(T == string)) { m_range.put('"'); m_range.jsonEscape(value); m_range.put('"'); } else static if (is(T == Json)) m_range.writeJsonString(value); else static if (isJsonSerializable!T) { static if (!__traits(compiles, () @safe { return value.toJson(); } ())) pragma(msg, "Non-@safe toJson/fromJson methods are deprecated - annotate "~T.stringof~".toJson() with @safe."); m_range.writeJsonString!(R, pretty)(() @trusted { return value.toJson(); } (), m_level); } else static assert(false, "Unsupported type: " ~ T.stringof); } private void startComposite() { static if (pretty) m_level++; m_firstInComposite = true; } private void startCompositeEntry() { if (!m_firstInComposite) { m_range.put(','); } else { m_firstInComposite = false; } static if (pretty) indent(); } private void endComposite() { static if (pretty) { m_level--; if (!m_firstInComposite) indent(); } m_firstInComposite = false; } private void indent() { m_range.put('\n'); foreach (i; 0 .. m_level) m_range.put('\t'); } } // // deserialization // static if (isInputRange!(R)) { private { int m_line = 0; } void readDictionary(Traits)(scope void delegate(string) @safe entry_callback) { m_range.skipWhitespace(&m_line); enforceJson(!m_range.empty && m_range.front == '{', "Expecting object."); m_range.popFront(); bool first = true; while(true) { m_range.skipWhitespace(&m_line); enforceJson(!m_range.empty, "Missing '}'."); if (m_range.front == '}') { m_range.popFront(); break; } else if (!first) { enforceJson(m_range.front == ',', "Expecting ',' or '}', not '"~m_range.front.to!string~"'."); m_range.popFront(); m_range.skipWhitespace(&m_line); } else first = false; auto name = m_range.skipJsonString(&m_line); m_range.skipWhitespace(&m_line); enforceJson(!m_range.empty && m_range.front == ':', "Expecting ':', not '"~m_range.front.to!string~"'."); m_range.popFront(); entry_callback(name); } } void beginReadDictionaryEntry(Traits)(string name) {} void endReadDictionaryEntry(Traits)(string name) {} void readArray(Traits)(scope void delegate(size_t) @safe size_callback, scope void delegate() @safe entry_callback) { m_range.skipWhitespace(&m_line); enforceJson(!m_range.empty && m_range.front == '[', "Expecting array."); m_range.popFront(); bool first = true; while(true) { m_range.skipWhitespace(&m_line); enforceJson(!m_range.empty, "Missing ']'."); if (m_range.front == ']') { m_range.popFront(); break; } else if (!first) { enforceJson(m_range.front == ',', "Expecting ',' or ']'."); m_range.popFront(); } else first = false; entry_callback(); } } void beginReadArrayEntry(Traits)(size_t index) {} void endReadArrayEntry(Traits)(size_t index) {} T readValue(Traits, T)() { m_range.skipWhitespace(&m_line); static if (is(T == typeof(null))) { enforceJson(m_range.take(4).equal("null"), "Expecting 'null'."); return null; } else static if (is(T == bool)) { bool ret = m_range.front == 't'; string expected = ret ? "true" : "false"; foreach (ch; expected) { enforceJson(m_range.front == ch, "Expecting 'true' or 'false'."); m_range.popFront(); } return ret; } else static if (is(T : long)) { bool is_float; bool is_long_overflow; auto num = m_range.skipNumber(is_float, is_long_overflow); enforceJson(!is_float, "Expecting integer number."); enforceJson(!is_long_overflow, num.to!string~" is too big for long."); return to!T(num); } else static if (is(T : BigInt)) { bool is_float; bool is_long_overflow; auto num = m_range.skipNumber(is_float, is_long_overflow); enforceJson(!is_float, "Expecting integer number."); return BigInt(num); } else static if (is(T : real)) { bool is_float; bool is_long_overflow; auto num = m_range.skipNumber(is_float, is_long_overflow); return to!T(num); } else static if (is(T == string)) return m_range.skipJsonString(&m_line); else static if (is(T == Json)) return m_range.parseJson(&m_line); else static if (isJsonSerializable!T) { static if (!__traits(compiles, () @safe { return T.fromJson(Json.init); } ())) pragma(msg, "Non-@safe toJson/fromJson methods are deprecated - annotate "~T.stringof~".fromJson() with @safe."); return () @trusted { return T.fromJson(m_range.parseJson(&m_line)); } (); } else static assert(false, "Unsupported type: " ~ T.stringof); } bool tryReadNull(Traits)() { m_range.skipWhitespace(&m_line); if (m_range.front != 'n') return false; foreach (ch; "null") { enforceJson(m_range.front == ch, "Expecting 'null'."); m_range.popFront(); } assert(m_range.empty || m_range.front != 'l'); return true; } } } unittest { assert(serializeToJsonString(double.nan) == "null"); assert(serializeToJsonString(Json()) == "null"); assert(serializeToJsonString(Json(["bar":Json("baz"),"foo":Json()])) == `{"bar":"baz"}`); struct Foo{Json bar = Json();} Foo f; assert(serializeToJsonString(f) == `{"bar":null}`); } /** Writes the given JSON object as a JSON string into the destination range. This function will convert the given JSON value to a string without adding any white space between tokens (no newlines, no indentation and no padding). The output size is thus minimized, at the cost of bad human readability. Params: dst = References the string output range to which the result is written. json = Specifies the JSON value that is to be stringified. See_Also: Json.toString, writePrettyJsonString */ void writeJsonString(R, bool pretty = false)(ref R dst, in Json json, size_t level = 0) @safe // if( isOutputRange!R && is(ElementEncodingType!R == char) ) { final switch( json.type ){ case Json.Type.undefined: dst.put("null"); break; case Json.Type.null_: dst.put("null"); break; case Json.Type.bool_: dst.put(json.get!bool ? "true" : "false"); break; case Json.Type.int_: formattedWrite(dst, "%d", json.get!long); break; case Json.Type.bigInt: () @trusted { formattedWrite(dst, "%d", json.get!BigInt); } (); break; case Json.Type.float_: auto d = json.get!double; if (d != d) dst.put("null"); // JSON has no NaN value so set null else formattedWrite(dst, "%.16g", json.get!double); break; case Json.Type.string: dst.put('\"'); jsonEscape(dst, json.get!string); dst.put('\"'); break; case Json.Type.array: dst.put('['); bool first = true; foreach (ref const Json e; json.byValue) { if( !first ) dst.put(","); first = false; static if (pretty) { dst.put('\n'); foreach (tab; 0 .. level+1) dst.put('\t'); } if (e.type == Json.Type.undefined) dst.put("null"); else writeJsonString!(R, pretty)(dst, e, level+1); } static if (pretty) { if (json.length > 0) { dst.put('\n'); foreach (tab; 0 .. level) dst.put('\t'); } } dst.put(']'); break; case Json.Type.object: dst.put('{'); bool first = true; foreach (string k, ref const Json e; json.byKeyValue) { if( e.type == Json.Type.undefined ) continue; if( !first ) dst.put(','); first = false; static if (pretty) { dst.put('\n'); foreach (tab; 0 .. level+1) dst.put('\t'); } dst.put('\"'); jsonEscape(dst, k); dst.put(pretty ? `": ` : `":`); writeJsonString!(R, pretty)(dst, e, level+1); } static if (pretty) { if (json.length > 0) { dst.put('\n'); foreach (tab; 0 .. level) dst.put('\t'); } } dst.put('}'); break; } } unittest { auto a = Json.emptyObject; a["a"] = Json.emptyArray; a["b"] = Json.emptyArray; a["b"] ~= Json(1); a["b"] ~= Json.emptyObject; assert(a.toString() == `{"a":[],"b":[1,{}]}` || a.toString() == `{"b":[1,{}],"a":[]}`); assert(a.toPrettyString() == `{ "a": [], "b": [ 1, {} ] }` || a.toPrettyString() == `{ "b": [ 1, {} ], "a": [] }`); } unittest { // #735 auto a = Json.emptyArray; a ~= "a"; a ~= Json(); a ~= "b"; a ~= null; a ~= "c"; assert(a.toString() == `["a",null,"b",null,"c"]`); } unittest { auto a = Json.emptyArray; a ~= Json(1); a ~= Json(2); a ~= Json(3); a ~= Json(4); a ~= Json(5); auto b = Json(a[0..a.length]); assert(a == b); auto c = Json(a[0..$]); assert(a == c); assert(b == c); auto d = [Json(1),Json(2),Json(3)]; assert(d == a[0..a.length-2]); assert(d == a[0..$-2]); } unittest { auto j = Json(double.init); assert(j.toString == "null"); // A double nan should serialize to null j = 17.04f; assert(j.toString == "17.04"); // A proper double should serialize correctly double d; deserializeJson(d, Json.undefined); // Json.undefined should deserialize to nan assert(d != d); deserializeJson(d, Json(null)); // Json.undefined should deserialize to nan assert(d != d); } /** Writes the given JSON object as a prettified JSON string into the destination range. The output will contain newlines and indents to make the output human readable. Params: dst = References the string output range to which the result is written. json = Specifies the JSON value that is to be stringified. level = Specifies the base amount of indentation for the output. Indentation is always done using tab characters. See_Also: Json.toPrettyString, writeJsonString */ void writePrettyJsonString(R)(ref R dst, in Json json, int level = 0) // if( isOutputRange!R && is(ElementEncodingType!R == char) ) { writeJsonString!(R, true)(dst, json, level); } /** Helper function that escapes all Unicode characters in a JSON string. */ string convertJsonToASCII(string json) { auto ret = appender!string; jsonEscape!true(ret, json); return ret.data; } /// private private void jsonEscape(bool escape_unicode = false, R)(ref R dst, string s) { char lastch; for (size_t pos = 0; pos < s.length; pos++) { immutable(char) ch = s[pos]; switch (ch) { default: static if (escape_unicode) { if (ch > 0x20 && ch < 0x80) dst.put(ch); else { import std.utf : decode; int len; dchar codepoint = decode(s, pos); /* codepoint is in BMP */ if(codepoint < 0x10000) { dst.formattedWrite("\\u%04X", codepoint); } /* not in BMP -> construct a UTF-16 surrogate pair */ else { int first, last; codepoint -= 0x10000; first = 0xD800 | ((codepoint & 0xffc00) >> 10); last = 0xDC00 | (codepoint & 0x003ff); dst.formattedWrite("\\u%04X\\u%04X", first, last); } pos -= 1; } } else { if (ch < 0x20) dst.formattedWrite("\\u%04X", ch); else dst.put(ch); } break; case '\\': dst.put("\\\\"); break; case '\r': dst.put("\\r"); break; case '\n': dst.put("\\n"); break; case '\t': dst.put("\\t"); break; case '\"': dst.put("\\\""); break; case '/': // this avoids the sequence "</" in the output, which is prone // to cross site scripting attacks when inserted into web pages if (lastch == '<') dst.put("\\/"); else dst.put(ch); break; } lastch = ch; } } /// private private string jsonUnescape(R)(ref R range) { auto ret = appender!string(); while(!range.empty){ auto ch = range.front; switch( ch ){ case '"': return ret.data; case '\\': range.popFront(); enforceJson(!range.empty, "Unterminated string escape sequence."); switch(range.front){ default: enforceJson(false, "Invalid string escape sequence."); break; case '"': ret.put('\"'); range.popFront(); break; case '\\': ret.put('\\'); range.popFront(); break; case '/': ret.put('/'); range.popFront(); break; case 'b': ret.put('\b'); range.popFront(); break; case 'f': ret.put('\f'); range.popFront(); break; case 'n': ret.put('\n'); range.popFront(); break; case 'r': ret.put('\r'); range.popFront(); break; case 't': ret.put('\t'); range.popFront(); break; case 'u': dchar decode_unicode_escape() { enforceJson(range.front == 'u'); range.popFront(); dchar uch = 0; foreach( i; 0 .. 4 ){ uch *= 16; enforceJson(!range.empty, "Unicode sequence must be '\\uXXXX'."); auto dc = range.front; range.popFront(); if( dc >= '0' && dc <= '9' ) uch += dc - '0'; else if( dc >= 'a' && dc <= 'f' ) uch += dc - 'a' + 10; else if( dc >= 'A' && dc <= 'F' ) uch += dc - 'A' + 10; else enforceJson(false, "Unicode sequence must be '\\uXXXX'."); } return uch; } auto uch = decode_unicode_escape(); if(0xD800 <= uch && uch <= 0xDBFF) { /* surrogate pair */ range.popFront(); // backslash '\' auto uch2 = decode_unicode_escape(); enforceJson(0xDC00 <= uch2 && uch2 <= 0xDFFF, "invalid Unicode"); { /* valid second surrogate */ uch = ((uch - 0xD800) << 10) + (uch2 - 0xDC00) + 0x10000; } } ret.put(uch); break; } break; default: ret.put(ch); range.popFront(); break; } } return ret.data; } private auto skipNumber(R)(ref R s, out bool is_float, out bool is_long_overflow) @safe if (isNarrowString!R) { auto r = s.representation; version (assert) auto rEnd = (() @trusted => r.ptr + r.length - 1)(); auto res = skipNumber(r, is_float, is_long_overflow); version (assert) assert(rEnd == (() @trusted => r.ptr + r.length - 1)()); // check nothing taken off the end s = s[$ - r.length .. $]; return res.assumeUTF(); } /// private private auto skipNumber(R)(ref R s, out bool is_float, out bool is_long_overflow) if (!isNarrowString!R && isForwardRange!R) { pragma(msg, R); auto sOrig = s.save; size_t idx = 0; is_float = false; is_long_overflow = false; ulong int_part = 0; if (s.front == '-') { s.popFront(); ++idx; } if (s.front == '0') { s.popFront(); ++idx; } else { enforceJson(isDigit(s.front), "Digit expected at beginning of number."); int_part = s.front - '0'; s.popFront(); ++idx; while( !s.empty && isDigit(s.front) ) { if (!is_long_overflow) { auto dig = s.front - '0'; if ((long.max / 10) > int_part || ((long.max / 10) == int_part && (long.max % 10) >= dig)) { int_part *= 10; int_part += dig; } else { is_long_overflow = true; } } s.popFront(); ++idx; } } if( !s.empty && s.front == '.' ) { s.popFront(); ++idx; is_float = true; while( !s.empty && isDigit(s.front) ) { s.popFront(); ++idx; } } if( !s.empty && (s.front == 'e' || s.front == 'E') ) { s.popFront(); ++idx; is_float = true; if( !s.empty && (s.front == '+' || s.front == '-') ) { s.popFront(); ++idx; } enforceJson( !s.empty && isDigit(s.front), "Expected exponent." ~ sOrig.takeExactly(idx).to!string); s.popFront(); ++idx; while( !s.empty && isDigit(s.front) ) { s.popFront(); ++idx; } } return sOrig.takeExactly(idx); } unittest { import std.meta : AliasSeq; // test for string and for a simple range foreach (foo; AliasSeq!(to!string, map!"a")) { auto test_1 = foo("9223372036854775806"); // lower then long.max auto test_2 = foo("9223372036854775807"); // long.max auto test_3 = foo("9223372036854775808"); // greater then long.max bool is_float; bool is_long_overflow; test_1.skipNumber(is_float, is_long_overflow); assert(!is_long_overflow); test_2.skipNumber(is_float, is_long_overflow); assert(!is_long_overflow); test_3.skipNumber(is_float, is_long_overflow); assert(is_long_overflow); } } /// private private string skipJsonString(R)(ref R s, int* line = null) { // TODO: count or disallow any newlines inside of the string enforceJson(!s.empty && s.front == '"', "Expected '\"' to start string."); s.popFront(); string ret = jsonUnescape(s); enforceJson(!s.empty && s.front == '"', "Expected '\"' to terminate string."); s.popFront(); return ret; } /// private private void skipWhitespace(R)(ref R s, int* line = null) { while (!s.empty) { switch (s.front) { default: return; case ' ', '\t': s.popFront(); break; case '\n': s.popFront(); if (!s.empty && s.front == '\r') s.popFront(); if (line) (*line)++; break; case '\r': s.popFront(); if (!s.empty && s.front == '\n') s.popFront(); if (line) (*line)++; break; } } } private bool isDigit(dchar ch) @safe nothrow pure { return ch >= '0' && ch <= '9'; } private string underscoreStrip(string field_name) @safe nothrow pure { if( field_name.length < 1 || field_name[$-1] != '_' ) return field_name; else return field_name[0 .. $-1]; } /// private package template isJsonSerializable(T) { enum isJsonSerializable = is(typeof(T.init.toJson()) == Json) && is(typeof(T.fromJson(Json())) == T); } private void enforceJson(string file = __FILE__, size_t line = __LINE__)(bool cond, lazy string message = "JSON exception") { enforceEx!JSONException(cond, message, file, line); } private void enforceJson(string file = __FILE__, size_t line = __LINE__)(bool cond, lazy string message, string err_file, int err_line) { enforceEx!JSONException(cond, format("%s(%s): Error: %s", err_file, err_line+1, message), file, line); } private void enforceJson(string file = __FILE__, size_t line = __LINE__)(bool cond, lazy string message, string err_file, int* err_line) { enforceJson!(file, line)(cond, message, err_file, err_line ? *err_line : -1); } private auto trustedRange(R)(R range) { static struct Rng { private R range; @property bool empty() @trusted { return range.empty; } @property auto front() @trusted { return range.front; } void popFront() @trusted { range.popFront(); } } return Rng(range); } // test for vibe.utils.DictionaryList @safe unittest { import vibe.utils.dictionarylist; static assert(isCustomSerializable!(DictionaryList!int)); DictionaryList!(int, false) b; b.addField("a", 1); b.addField("A", 2); auto app = appender!string(); serializeToJson(app, b); assert(app.data == `[{"key":"a","value":1},{"key":"A","value":2}]`, app.data); DictionaryList!(int, true, 2) c; c.addField("a", 1); c.addField("b", 2); c.addField("a", 3); c.remove("b"); auto appc = appender!string(); serializeToJson(appc, c); assert(appc.data == `[{"key":"a","value":1},{"key":"a","value":3}]`, appc.data); } // make sure Json is usable for CTFE @safe unittest { static assert(is(typeof({ struct Test { Json object_ = Json.emptyObject; Json array = Json.emptyArray; } })), "CTFE for Json type failed."); static Json test() { Json j; j = Json(42); j = Json([Json(true)]); j = Json(["foo": Json(null)]); j = Json("foo"); return j; } enum j = test(); static assert(j == Json("foo")); } @safe unittest { // XSS prevention assert(Json("</script>some/path").toString() == `"<\/script>some/path"`); assert(serializeToJsonString("</script>some/path") == `"<\/script>some/path"`); } @system unittest { // Recursive structures static struct Bar { Bar[] foos; int i; } auto b = deserializeJson!Bar(`{"i":1,"foos":[{"foos":[],"i":2}]}`); assert(b.i == 1); assert(b.foos.length == 1); assert(b.foos[0].i == 2); assert(b.foos[0].foos.length == 0); }