-
-
Notifications
You must be signed in to change notification settings - Fork 709
/
Copy pathjson.d
2750 lines (2455 loc) · 82.2 KB
/
json.d
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
// Written in the D programming language.
/**
Implements functionality to read and write JavaScript Object Notation values.
JavaScript Object Notation is a lightweight data interchange format commonly used in web services and configuration files.
It's easy for humans to read and write, and it's easy for machines to parse and generate.
$(RED Warning: While $(LREF JSONValue) is fine for small-scale use, at the range of hundreds of megabytes it is
known to cause and exacerbate GC problems. If you encounter problems, try replacing it with a stream parser. See
also $(LINK https://forum.dlang.org/post/dzfyaxypmkdrpakmycjv@forum.dlang.org).)
Copyright: Copyright Jeremie Pelletier 2008 - 2009.
License: $(HTTP www.boost.org/LICENSE_1_0.txt, Boost License 1.0).
Authors: Jeremie Pelletier, David Herberth
References: $(LINK http://json.org/), $(LINK https://seriot.ch/projects/parsing_json.html)
Source: $(PHOBOSSRC std/json.d)
*/
/*
Copyright Jeremie Pelletier 2008 - 2009.
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
module std.json;
import std.array;
import std.conv;
import std.range;
import std.traits;
///
@system unittest
{
import std.conv : to;
// parse a file or string of json into a usable structure
string s = `{ "language": "D", "rating": 3.5, "code": "42" }`;
JSONValue j = parseJSON(s);
// j and j["language"] return JSONValue,
// j["language"].str returns a string
assert(j["language"].str == "D");
assert(j["rating"].floating == 3.5);
// check a type
long x;
if (const(JSONValue)* code = "code" in j)
{
if (code.type() == JSONType.integer)
x = code.integer;
else
x = to!int(code.str);
}
// create a json struct
JSONValue jj = [ "language": "D" ];
// rating doesnt exist yet, so use .object to assign
jj.object["rating"] = JSONValue(3.5);
// create an array to assign to list
jj.object["list"] = JSONValue( ["a", "b", "c"] );
// list already exists, so .object optional
jj["list"].array ~= JSONValue("D");
string jjStr = `{"language":"D","list":["a","b","c","D"],"rating":3.5}`;
assert(jj.toString == jjStr);
}
/**
String literals used to represent special float values within JSON strings.
*/
enum JSONFloatLiteral : string
{
nan = "NaN", /// String representation of floating-point NaN
inf = "Infinite", /// String representation of floating-point Infinity
negativeInf = "-Infinite", /// String representation of floating-point negative Infinity
}
/**
Flags that control how JSON is encoded and parsed.
*/
enum JSONOptions
{
none, /// Standard parsing and encoding
specialFloatLiterals = 0x1, /// Encode NaN and Inf float values as strings
escapeNonAsciiChars = 0x2, /// Encode non-ASCII characters with a Unicode escape sequence
doNotEscapeSlashes = 0x4, /// Do not escape slashes ('/')
strictParsing = 0x8, /// Strictly follow RFC-8259 grammar when parsing
preserveObjectOrder = 0x16, /// Preserve order of object keys when parsing
}
/**
Enumeration of JSON types
*/
enum JSONType : byte
{
/// Indicates the type of a `JSONValue`.
null_,
string, /// ditto
integer, /// ditto
uinteger, /// ditto
float_, /// ditto
array, /// ditto
object, /// ditto
true_, /// ditto
false_, /// ditto
// FIXME: Find some way to deprecate the enum members below, which does NOT
// create lots of spam-like deprecation warnings, which can't be fixed
// by the user. See discussion on this issue at
// https://forum.dlang.org/post/feudrhtxkaxxscwhhhff@forum.dlang.org
/* deprecated("Use .null_") */ NULL = null_,
/* deprecated("Use .string") */ STRING = string,
/* deprecated("Use .integer") */ INTEGER = integer,
/* deprecated("Use .uinteger") */ UINTEGER = uinteger,
/* deprecated("Use .float_") */ FLOAT = float_,
/* deprecated("Use .array") */ ARRAY = array,
/* deprecated("Use .object") */ OBJECT = object,
/* deprecated("Use .true_") */ TRUE = true_,
/* deprecated("Use .false_") */ FALSE = false_,
}
deprecated("Use JSONType and the new enum member names") alias JSON_TYPE = JSONType;
/**
JSON value node
*/
struct JSONValue
{
import std.exception : enforce;
import std.typecons : Tuple;
alias OrderedObjectMember = Tuple!(
string, "key",
JSONValue, "value",
);
union Store
{
struct Object
{
bool isOrdered;
union
{
JSONValue[string] unordered;
OrderedObjectMember[] ordered;
}
}
string str;
long integer;
ulong uinteger;
double floating;
Object object;
JSONValue[] array;
}
private Store store;
private JSONType type_tag;
/**
Returns the JSONType of the value stored in this structure.
*/
@property JSONType type() const pure nothrow @safe @nogc
{
return type_tag;
}
///
@safe unittest
{
string s = "{ \"language\": \"D\" }";
JSONValue j = parseJSON(s);
assert(j.type == JSONType.object);
assert(j["language"].type == JSONType.string);
}
/***
* Value getter/setter for `JSONType.string`.
* Throws: `JSONException` for read access if `type` is not
* `JSONType.string`.
*/
@property string str() const pure @trusted return scope
{
enforce!JSONException(type == JSONType.string,
"JSONValue is not a string");
return store.str;
}
/// ditto
@property string str(return scope string v) pure nothrow @nogc @trusted return // TODO make @safe
{
assign(v);
return v;
}
///
@safe unittest
{
JSONValue j = [ "language": "D" ];
// get value
assert(j["language"].str == "D");
// change existing key to new string
j["language"].str = "Perl";
assert(j["language"].str == "Perl");
}
/***
* Value getter/setter for `JSONType.integer`.
* Throws: `JSONException` for read access if `type` is not
* `JSONType.integer`.
*/
@property long integer() const pure @safe
{
enforce!JSONException(type == JSONType.integer,
"JSONValue is not an integer");
return store.integer;
}
/// ditto
@property long integer(long v) pure nothrow @safe @nogc
{
assign(v);
return store.integer;
}
/***
* Value getter/setter for `JSONType.uinteger`.
* Throws: `JSONException` for read access if `type` is not
* `JSONType.uinteger`.
*/
@property ulong uinteger() const pure @safe
{
enforce!JSONException(type == JSONType.uinteger,
"JSONValue is not an unsigned integer");
return store.uinteger;
}
/// ditto
@property ulong uinteger(ulong v) pure nothrow @safe @nogc
{
assign(v);
return store.uinteger;
}
/***
* Value getter/setter for `JSONType.float_`. Note that despite
* the name, this is a $(B 64)-bit `double`, not a 32-bit `float`.
* Throws: `JSONException` for read access if `type` is not
* `JSONType.float_`.
*/
@property double floating() const pure @safe
{
enforce!JSONException(type == JSONType.float_,
"JSONValue is not a floating type");
return store.floating;
}
/// ditto
@property double floating(double v) pure nothrow @safe @nogc
{
assign(v);
return store.floating;
}
/***
* Value getter/setter for boolean stored in JSON.
* Throws: `JSONException` for read access if `this.type` is not
* `JSONType.true_` or `JSONType.false_`.
*/
@property bool boolean() const pure @safe
{
if (type == JSONType.true_) return true;
if (type == JSONType.false_) return false;
throw new JSONException("JSONValue is not a boolean type");
}
/// ditto
@property bool boolean(bool v) pure nothrow @safe @nogc
{
assign(v);
return v;
}
///
@safe unittest
{
JSONValue j = true;
assert(j.boolean == true);
j.boolean = false;
assert(j.boolean == false);
j.integer = 12;
import std.exception : assertThrown;
assertThrown!JSONException(j.boolean);
}
/***
* Value getter/setter for unordered `JSONType.object`.
* Throws: `JSONException` for read access if `type` is not
* `JSONType.object` or the object is ordered.
* Note: This is @system because of the following pattern:
---
auto a = &(json.object());
json.uinteger = 0; // overwrite AA pointer
(*a)["hello"] = "world"; // segmentation fault
---
*/
@property ref inout(JSONValue[string]) object() inout pure @system return
{
enforce!JSONException(type == JSONType.object,
"JSONValue is not an object");
enforce!JSONException(!store.object.isOrdered,
"JSONValue object is ordered, cannot return by ref");
return store.object.unordered;
}
/// ditto
@property JSONValue[string] object(return scope JSONValue[string] v) pure nothrow @nogc @trusted // TODO make @safe
{
assign(v);
return v;
}
/***
* Value getter for unordered `JSONType.object`.
* Unlike `object`, this retrieves the object by value
* and can be used in @safe code.
*
* One possible caveat is that, if the returned value is null,
* modifications will not be visible:
* ---
* JSONValue json;
* json.object = null;
* json.objectNoRef["hello"] = JSONValue("world");
* assert("hello" !in json.object);
* ---
*
* Throws: `JSONException` for read access if `type` is not
* `JSONType.object`.
*/
@property inout(JSONValue[string]) objectNoRef() inout pure @trusted
{
enforce!JSONException(type == JSONType.object,
"JSONValue is not an object");
if (store.object.isOrdered)
{
// Convert to unordered
JSONValue[string] result;
foreach (pair; store.object.ordered)
result[pair.key] = pair.value;
return cast(inout) result;
}
else
return store.object.unordered;
}
/***
* Value getter/setter for ordered `JSONType.object`.
* Throws: `JSONException` for read access if `type` is not
* `JSONType.object` or the object is unordered.
* Note: This is @system because of the following pattern:
---
auto a = &(json.orderedObject());
json.uinteger = 0; // overwrite AA pointer
(*a)["hello"] = "world"; // segmentation fault
---
*/
@property ref inout(OrderedObjectMember[]) orderedObject() inout pure @system return
{
enforce!JSONException(type == JSONType.object,
"JSONValue is not an object");
enforce!JSONException(store.object.isOrdered,
"JSONValue object is unordered, cannot return by ref");
return store.object.ordered;
}
/// ditto
@property OrderedObjectMember[] orderedObject(return scope OrderedObjectMember[] v) pure nothrow @nogc @trusted // TODO make @safe
{
assign(v);
return v;
}
/***
* Value getter for ordered `JSONType.object`.
* Unlike `orderedObject`, this retrieves the object by value
* and can be used in @safe code.
*/
@property inout(OrderedObjectMember[]) orderedObjectNoRef() inout pure @trusted
{
enforce!JSONException(type == JSONType.object,
"JSONValue is not an object");
if (store.object.isOrdered)
return store.object.ordered;
else
{
// Convert to ordered
OrderedObjectMember[] result;
foreach (key, value; store.object.unordered)
result ~= OrderedObjectMember(key, value);
return cast(inout) result;
}
}
/// Returns `true` if the order of keys of the represented object is being preserved.
@property bool isOrdered() const pure @trusted
{
enforce!JSONException(type == JSONType.object,
"JSONValue is not an object");
return store.object.isOrdered;
}
/***
* Value getter/setter for `JSONType.array`.
* Throws: `JSONException` for read access if `type` is not
* `JSONType.array`.
* Note: This is @system because of the following pattern:
---
auto a = &(json.array());
json.uinteger = 0; // overwrite array pointer
(*a)[0] = "world"; // segmentation fault
---
*/
@property ref inout(JSONValue[]) array() scope return inout pure @system
{
enforce!JSONException(type == JSONType.array,
"JSONValue is not an array");
return store.array;
}
/// ditto
@property JSONValue[] array(return scope JSONValue[] v) pure nothrow @nogc @trusted scope // TODO make @safe
{
assign(v);
return v;
}
/***
* Value getter for `JSONType.array`.
* Unlike `array`, this retrieves the array by value and can be used in @safe code.
*
* One possible caveat is that, if you append to the returned array,
* the new values aren't visible in the `JSONValue`:
* ---
* JSONValue json;
* json.array = [JSONValue("hello")];
* json.arrayNoRef ~= JSONValue("world");
* assert(json.array.length == 1);
* ---
*
* Throws: `JSONException` for read access if `type` is not
* `JSONType.array`.
*/
@property inout(JSONValue[]) arrayNoRef() inout pure @trusted
{
enforce!JSONException(type == JSONType.array,
"JSONValue is not an array");
return store.array;
}
/// Test whether the type is `JSONType.null_`
@property bool isNull() const pure nothrow @safe @nogc
{
return type == JSONType.null_;
}
/***
* A convenience getter that returns this `JSONValue` as the specified D type.
* Note: Only numeric types, `bool`, `string`, `JSONValue[string]`, and `JSONValue[]` types are accepted
* Throws: `JSONException` if `T` cannot hold the contents of this `JSONValue`
* `ConvException` in case of integer overflow when converting to `T`
*/
@property inout(T) get(T)() inout const pure @safe
{
static if (is(immutable T == immutable string))
{
return str;
}
else static if (is(immutable T == immutable bool))
{
return boolean;
}
else static if (isFloatingPoint!T)
{
switch (type)
{
case JSONType.float_:
return cast(T) floating;
case JSONType.uinteger:
return cast(T) uinteger;
case JSONType.integer:
return cast(T) integer;
default:
throw new JSONException("JSONValue is not a number type");
}
}
else static if (isIntegral!T)
{
switch (type)
{
case JSONType.uinteger:
return uinteger.to!T;
case JSONType.integer:
return integer.to!T;
default:
throw new JSONException("JSONValue is not a an integral type");
}
}
else
{
static assert(false, "Unsupported type");
}
}
// This specialization is needed because arrayNoRef requires inout
@property inout(T) get(T : JSONValue[])() inout pure @trusted /// ditto
{
return arrayNoRef;
}
/// ditto
@property inout(T) get(T : JSONValue[string])() inout pure @trusted
{
return object;
}
///
@safe unittest
{
import std.exception;
import std.conv;
string s =
`{
"a": 123,
"b": 3.1415,
"c": "text",
"d": true,
"e": [1, 2, 3],
"f": { "a": 1 },
"g": -45,
"h": ` ~ ulong.max.to!string ~ `,
}`;
struct a { }
immutable json = parseJSON(s);
assert(json["a"].get!double == 123.0);
assert(json["a"].get!int == 123);
assert(json["a"].get!uint == 123);
assert(json["b"].get!double == 3.1415);
assertThrown!JSONException(json["b"].get!int);
assert(json["c"].get!string == "text");
assert(json["d"].get!bool == true);
assertNotThrown(json["e"].get!(JSONValue[]));
assertNotThrown(json["f"].get!(JSONValue[string]));
static assert(!__traits(compiles, json["a"].get!a));
assertThrown!JSONException(json["e"].get!float);
assertThrown!JSONException(json["d"].get!(JSONValue[string]));
assertThrown!JSONException(json["f"].get!(JSONValue[]));
assert(json["g"].get!int == -45);
assertThrown!ConvException(json["g"].get!uint);
assert(json["h"].get!ulong == ulong.max);
assertThrown!ConvException(json["h"].get!uint);
assertNotThrown(json["h"].get!float);
}
private void assign(T)(T arg)
{
static if (is(T : typeof(null)))
{
type_tag = JSONType.null_;
}
else static if (is(T : string))
{
type_tag = JSONType.string;
string t = arg;
() @trusted { store.str = t; }();
}
// https://issues.dlang.org/show_bug.cgi?id=15884
else static if (isSomeString!T)
{
type_tag = JSONType.string;
// FIXME: std.Array.Array(Range) is not deduced as 'pure'
() @trusted {
import std.utf : byUTF;
store.str = cast(immutable)(arg.byUTF!char.array);
}();
}
else static if (is(T : bool))
{
type_tag = arg ? JSONType.true_ : JSONType.false_;
}
else static if (is(T : ulong) && isUnsigned!T)
{
type_tag = JSONType.uinteger;
store.uinteger = arg;
}
else static if (is(T : long))
{
type_tag = JSONType.integer;
store.integer = arg;
}
else static if (isFloatingPoint!T)
{
type_tag = JSONType.float_;
store.floating = arg;
}
else static if (is(T : Value[Key], Key, Value))
{
static assert(is(Key : string), "AA key must be string");
type_tag = JSONType.object;
static if (is(Value : JSONValue))
{
JSONValue[string] t = arg;
() @trusted {
store.object.isOrdered = false;
store.object.unordered = t;
}();
}
else
{
JSONValue[string] aa;
foreach (key, value; arg)
aa[key] = JSONValue(value);
() @trusted {
store.object.isOrdered = false;
store.object.unordered = aa;
}();
}
}
else static if (is(T : OrderedObjectMember[]))
{
type_tag = JSONType.object;
() @trusted {
store.object.isOrdered = true;
store.object.ordered = arg;
}();
}
else static if (isArray!T)
{
type_tag = JSONType.array;
static if (is(ElementEncodingType!T : JSONValue))
{
JSONValue[] t = arg;
() @trusted { store.array = t; }();
}
else
{
JSONValue[] new_arg = new JSONValue[arg.length];
foreach (i, e; arg)
new_arg[i] = JSONValue(e);
() @trusted { store.array = new_arg; }();
}
}
else static if (is(T : JSONValue))
{
type_tag = arg.type;
store = arg.store;
}
else
{
static assert(false, text(`unable to convert type "`, T.stringof, `" to json`));
}
}
private void assignRef(T)(ref T arg)
if (isStaticArray!T)
{
type_tag = JSONType.array;
static if (is(ElementEncodingType!T : JSONValue))
{
store.array = arg;
}
else
{
JSONValue[] new_arg = new JSONValue[arg.length];
foreach (i, e; arg)
new_arg[i] = JSONValue(e);
store.array = new_arg;
}
}
/**
* Constructor for `JSONValue`. If `arg` is a `JSONValue`
* its value and type will be copied to the new `JSONValue`.
* Note that this is a shallow copy: if type is `JSONType.object`
* or `JSONType.array` then only the reference to the data will
* be copied.
* Otherwise, `arg` must be implicitly convertible to one of the
* following types: `typeof(null)`, `string`, `ulong`,
* `long`, `double`, an associative array `V[K]` for any `V`
* and `K` i.e. a JSON object, any array or `bool`. The type will
* be set accordingly.
*/
this(T)(T arg)
if (!isStaticArray!T)
{
assign(arg);
}
/// Ditto
this(T)(ref T arg)
if (isStaticArray!T)
{
assignRef(arg);
}
/// Ditto
this(T : JSONValue)(inout T arg) inout
{
store = arg.store;
type_tag = arg.type;
}
///
@safe unittest
{
JSONValue j = JSONValue( "a string" );
j = JSONValue(42);
j = JSONValue( [1, 2, 3] );
assert(j.type == JSONType.array);
j = JSONValue( ["language": "D"] );
assert(j.type == JSONType.object);
}
/**
* An enum value that can be used to obtain a `JSONValue` representing
* an empty JSON object.
*/
enum emptyObject = JSONValue(string[string].init);
///
@system unittest
{
JSONValue obj1 = JSONValue.emptyObject;
assert(obj1.type == JSONType.object);
obj1.object["a"] = JSONValue(1);
assert(obj1.object["a"] == JSONValue(1));
JSONValue obj2 = JSONValue.emptyObject;
assert("a" !in obj2.object);
obj2.object["b"] = JSONValue(5);
assert(obj1 != obj2);
}
/**
* An enum value that can be used to obtain a `JSONValue` representing
* an empty JSON object.
* Unlike `emptyObject`, the order of inserted keys is preserved.
*/
enum emptyOrderedObject = {
JSONValue v = void;
v.orderedObject = null;
return v;
}();
///
@system unittest
{
JSONValue obj = JSONValue.emptyOrderedObject;
assert(obj.type == JSONType.object);
assert(obj.isOrdered);
obj["b"] = JSONValue(2);
obj["a"] = JSONValue(1);
assert(obj["a"] == JSONValue(1));
assert(obj["b"] == JSONValue(2));
string[] keys;
foreach (string k, JSONValue v; obj)
keys ~= k;
assert(keys == ["b", "a"]);
}
/**
* An enum value that can be used to obtain a `JSONValue` representing
* an empty JSON array.
*/
enum emptyArray = JSONValue(JSONValue[].init);
///
@system unittest
{
JSONValue arr1 = JSONValue.emptyArray;
assert(arr1.type == JSONType.array);
assert(arr1.array.length == 0);
arr1.array ~= JSONValue("Hello");
assert(arr1.array.length == 1);
assert(arr1.array[0] == JSONValue("Hello"));
JSONValue arr2 = JSONValue.emptyArray;
assert(arr2.array.length == 0);
assert(arr1 != arr2);
}
void opAssign(T)(T arg)
if (!isStaticArray!T && !is(T : JSONValue))
{
assign(arg);
}
void opAssign(T)(ref T arg)
if (isStaticArray!T)
{
assignRef(arg);
}
/***
* Array syntax for JSON arrays.
* Throws: `JSONException` if `type` is not `JSONType.array`.
*/
ref inout(JSONValue) opIndex(size_t i) inout pure @safe
{
auto a = this.arrayNoRef;
enforce!JSONException(i < a.length,
"JSONValue array index is out of range");
return a[i];
}
///
@safe unittest
{
JSONValue j = JSONValue( [42, 43, 44] );
assert( j[0].integer == 42 );
assert( j[1].integer == 43 );
}
/***
* Hash syntax for JSON objects.
* Throws: `JSONException` if `type` is not `JSONType.object`.
*/
ref inout(JSONValue) opIndex(return scope string k) inout pure @safe
{
auto o = this.objectNoRef;
return *enforce!JSONException(k in o,
"Key not found: " ~ k);
}
///
@safe unittest
{
JSONValue j = JSONValue( ["language": "D"] );
assert( j["language"].str == "D" );
}
/***
* Provides support for index assignments, which sets the
* corresponding value of the JSON object's `key` field to `value`.
*
* If the `JSONValue` is `JSONType.null_`, then this function
* initializes it with a JSON object and then performs
* the index assignment.
*
* Throws: `JSONException` if `type` is not `JSONType.object`
* or `JSONType.null_`.
*/
void opIndexAssign(T)(auto ref T value, string key)
{
enforce!JSONException(
type == JSONType.object ||
type == JSONType.null_,
"JSONValue must be object or null");
if (type == JSONType.object && isOrdered)
{
auto arr = this.orderedObjectNoRef;
foreach (ref pair; arr)
if (pair.key == key)
{
pair.value = value;
return;
}
arr ~= OrderedObjectMember(key, JSONValue(value));
this.orderedObject = arr;
}
else
{
JSONValue[string] aa = null;
if (type == JSONType.object)
{
aa = this.objectNoRef;
}
aa[key] = value;
this.object = aa;
}
}
///
@safe unittest
{
JSONValue j = JSONValue( ["language": "D"] );
j["language"].str = "Perl";
assert( j["language"].str == "Perl" );
}
/// ditto
void opIndexAssign(T)(T arg, size_t i)
{
auto a = this.arrayNoRef;
enforce!JSONException(i < a.length,
"JSONValue array index is out of range");
a[i] = arg;
this.array = a;
}
///
@safe unittest
{
JSONValue j = JSONValue( ["Perl", "C"] );
j[1].str = "D";
assert( j[1].str == "D" );
}
JSONValue opBinary(string op : "~", T)(T arg)
{
auto a = this.arrayNoRef;
static if (isArray!T)
{
return JSONValue(a ~ JSONValue(arg).arrayNoRef);
}
else static if (is(T : JSONValue))
{
return JSONValue(a ~ arg.arrayNoRef);
}
else
{
static assert(false, "argument is not an array or a JSONValue array");
}
}
void opOpAssign(string op : "~", T)(T arg)
{
auto a = this.arrayNoRef;
static if (isArray!T)
{
a ~= JSONValue(arg).arrayNoRef;
}
else static if (is(T : JSONValue))
{
a ~= arg.arrayNoRef;
}
else
{
static assert(false, "argument is not an array or a JSONValue array");
}
this.array = a;
}
/**
* Provides support for the `in` operator.
*
* Tests whether a key can be found in an object.
*
* Returns:
* When found, the `inout(JSONValue)*` that matches to the key,
* otherwise `null`.
*
* Throws: `JSONException` if the right hand side argument `JSONType`
* is not `object`.
*/
inout(JSONValue)* opBinaryRight(string op : "in")(string k) inout @safe
{
return k in this.objectNoRef;
}
///
@safe unittest
{
JSONValue j = [ "language": "D", "author": "walter" ];
string a = ("author" in j).str;
*("author" in j) = "Walter";
assert(j["author"].str == "Walter");
}
/**
* Compare two JSONValues for equality
*
* JSON arrays and objects are compared deeply. The order of object keys does not matter.
*
* Floating point numbers are compared for exact equality, not approximal equality.
*
* Different number types (unsigned, signed, and floating) will be compared by converting
* them to a common type, in the same way that comparison of built-in D `int`, `uint` and
* `float` works.
*
* Other than that, types must match exactly.
* Empty arrays are not equal to empty objects, and booleans are never equal to integers.
*
* Returns: whether this `JSONValue` is equal to `rhs`
*/
bool opEquals(const JSONValue rhs) const @nogc nothrow pure @safe
{
return opEquals(rhs);
}
/// ditto
bool opEquals(ref const JSONValue rhs) const @nogc nothrow pure @trusted
{
import std.algorithm.searching : canFind;
// Default doesn't work well since store is a union. Compare only
// what should be in store.
// This is @trusted to remain nogc, nothrow, fast, and usable from @safe code.
final switch (type_tag)
{
case JSONType.integer:
switch (rhs.type_tag)
{
case JSONType.integer:
return store.integer == rhs.store.integer;
case JSONType.uinteger:
return store.integer == rhs.store.uinteger;
case JSONType.float_:
return store.integer == rhs.store.floating;
default:
return false;
}
case JSONType.uinteger:
switch (rhs.type_tag)
{