/usr/include/d/4.9/std/json.d is in libphobos-4.9-dev 4.9.3-13ubuntu2.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 | // Written in the D programming language.
/**
JavaScript Object Notation
Copyright: Copyright Jeremie Pelletier 2008 - 2009.
License: <a href="http://www.boost.org/LICENSE_1_0.txt">Boost License 1.0</a>.
Authors: Jeremie Pelletier, David Herberth
References: $(LINK http://json.org/)
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.ascii;
import std.conv;
import std.range;
import std.utf;
import std.traits;
import std.exception;
private
{
// Prevent conflicts from these generic names
alias std.utf.stride UTFStride;
alias std.utf.decode toUnicode;
}
/**
JSON type enumeration
*/
enum JSON_TYPE : byte
{
/// Indicates the type of a $(D JSONValue).
STRING,
INTEGER, /// ditto
UINTEGER,/// ditto
FLOAT, /// ditto
OBJECT, /// ditto
ARRAY, /// ditto
TRUE, /// ditto
FALSE, /// ditto
NULL /// ditto
}
/**
JSON value node
*/
struct JSONValue
{
union Store
{
string str;
long integer;
ulong uinteger;
real floating;
JSONValue[string] object;
JSONValue[] array;
}
private Store store;
private JSON_TYPE type_tag;
/// Specifies the _type of the value stored in this structure.
@property JSON_TYPE type() const
{
return type_tag;
}
/// Sets the _type of this $(D JSONValue). Previous content is cleared.
/// $(RED Scheduled for deprecation in September 2014. Instead, please
/// assign the value with the adequate type to $(D JSONValue) directly.)
@property JSON_TYPE type(JSON_TYPE newType)
{
if (type_tag != newType
&& ((type_tag != JSON_TYPE.INTEGER && type_tag != JSON_TYPE.UINTEGER)
|| (newType != JSON_TYPE.INTEGER && newType != JSON_TYPE.UINTEGER)))
{
final switch (newType)
{
case JSON_TYPE.STRING:
store.str = store.str.init;
break;
case JSON_TYPE.INTEGER:
store.integer = store.integer.init;
break;
case JSON_TYPE.UINTEGER:
store.uinteger = store.uinteger.init;
break;
case JSON_TYPE.FLOAT:
store.floating = store.floating.init;
break;
case JSON_TYPE.OBJECT:
store.object = store.object.init;
break;
case JSON_TYPE.ARRAY:
store.array = store.array.init;
break;
case JSON_TYPE.TRUE:
case JSON_TYPE.FALSE:
case JSON_TYPE.NULL:
break;
}
}
return type_tag = newType;
}
/// Value getter/setter for $(D JSON_TYPE.STRING).
/// Throws $(D JSONException) for read access if $(D type) is not $(D JSON_TYPE.STRING).
@property inout(string) str() inout
{
enforceEx!JSONException(type == JSON_TYPE.STRING,
"JSONValue is not a string");
return store.str;
}
/// ditto
@property string str(string v)
{
assign(v);
return store.str;
}
/// Value getter/setter for $(D JSON_TYPE.INTEGER).
/// Throws $(D JSONException) for read access if $(D type) is not $(D JSON_TYPE.INTEGER).
@property inout(long) integer() inout
{
enforceEx!JSONException(type == JSON_TYPE.INTEGER,
"JSONValue is not an integer");
return store.integer;
}
/// ditto
@property long integer(long v)
{
assign(v);
return store.integer;
}
/// Value getter/setter for $(D JSON_TYPE.UINTEGER).
/// Throws $(D JSONException) for read access if $(D type) is not $(D JSON_TYPE.UINTEGER).
@property inout(ulong) uinteger() inout
{
enforceEx!JSONException(type == JSON_TYPE.UINTEGER,
"JSONValue is not an unsigned integer");
return store.uinteger;
}
/// ditto
@property ulong uinteger(ulong v)
{
assign(v);
return store.uinteger;
}
/// Value getter/setter for $(D JSON_TYPE.FLOAT).
/// Throws $(D JSONException) for read access if $(D type) is not $(D JSON_TYPE.FLOAT).
@property inout(real) floating() inout
{
enforceEx!JSONException(type == JSON_TYPE.FLOAT,
"JSONValue is not a floating type");
return store.floating;
}
/// ditto
@property real floating(real v)
{
assign(v);
return store.floating;
}
/// Value getter/setter for $(D JSON_TYPE.OBJECT).
/// Throws $(D JSONException) for read access if $(D type) is not $(D JSON_TYPE.OBJECT).
@property ref inout(JSONValue[string]) object() inout
{
enforceEx!JSONException(type == JSON_TYPE.OBJECT,
"JSONValue is not an object");
return store.object;
}
/// ditto
@property JSONValue[string] object(JSONValue[string] v)
{
assign(v);
return store.object;
}
/// Value getter/setter for $(D JSON_TYPE.ARRAY).
/// Throws $(D JSONException) for read access if $(D type) is not $(D JSON_TYPE.ARRAY).
@property ref inout(JSONValue[]) array() inout
{
enforceEx!JSONException(type == JSON_TYPE.ARRAY,
"JSONValue is not an array");
return store.array;
}
/// ditto
@property JSONValue[] array(JSONValue[] v)
{
assign(v);
return store.array;
}
private void assign(T)(T arg)
{
static if(is(T : typeof(null)))
{
type_tag = JSON_TYPE.NULL;
}
else static if(is(T : string))
{
type_tag = JSON_TYPE.STRING;
store.str = arg;
}
else static if(is(T : bool))
{
type_tag = arg ? JSON_TYPE.TRUE : JSON_TYPE.FALSE;
}
else static if(is(T : ulong) && isUnsigned!T)
{
type_tag = JSON_TYPE.UINTEGER;
store.uinteger = arg;
}
else static if(is(T : long))
{
type_tag = JSON_TYPE.INTEGER;
store.integer = arg;
}
else static if(isFloatingPoint!T)
{
type_tag = JSON_TYPE.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 = JSON_TYPE.OBJECT;
static if(is(Value : JSONValue)) {
store.object = arg;
}
else
{
JSONValue[string] aa;
foreach(key, value; arg)
aa[key] = JSONValue(value);
store.object = aa;
}
}
else static if(isArray!T)
{
type_tag = JSON_TYPE.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;
}
}
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 = JSON_TYPE.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 $(D JSONValue). If $(D arg) is a $(D JSONValue)
* its value and type will be copied to the new $(D JSONValue).
* Note that this is a shallow copy: if type is $(D JSON_TYPE.OBJECT)
* or $(D JSON_TYPE.ARRAY) then only the reference to the data will
* be copied.
* Otherwise, $(D arg) must be implicitly convertible to one of the
* following types: $(D typeof(null)), $(D string), $(D ulong),
* $(D long), $(D real), an associative array $(D V[K]) for any $(D V)
* and $(D K) i.e. a JSON object, any array or $(D 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;
}
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 $(D JSONException) if $(D type) is not $(D JSON_TYPE.ARRAY).
ref inout(JSONValue) opIndex(size_t i) inout
{
enforceEx!JSONException(type == JSON_TYPE.ARRAY,
"JSONValue is not an array");
return store.array[i];
}
/// Hash syntax for json objects.
/// Throws $(D JSONException) if $(D type) is not $(D JSON_TYPE.OBJECT).
ref inout(JSONValue) opIndex(string k) inout
{
enforceEx!JSONException(type == JSON_TYPE.OBJECT,
"JSONValue is not an object");
return store.object[k];
}
/// Implements the foreach $(D opApply) interface for json arrays.
int opApply(int delegate(size_t index, ref JSONValue) dg)
{
enforceEx!JSONException(type == JSON_TYPE.ARRAY,
"JSONValue is not an array");
int result;
foreach(size_t index, ref value; store.array)
{
result = dg(index, value);
if(result)
break;
}
return result;
}
/// Implements the foreach $(D opApply) interface for json objects.
int opApply(int delegate(string key, ref JSONValue) dg)
{
enforceEx!JSONException(type == JSON_TYPE.OBJECT,
"JSONValue is not an object");
int result;
foreach(string key, ref value; store.object)
{
result = dg(key, value);
if(result)
break;
}
return result;
}
/// Implicitly calls $(D toJSON) on this JSONValue.
string toString()
{
return toJSON(&this);
}
/// Implicitly calls $(D toJSON) on this JSONValue, like $(D toString), but
/// also passes $(I true) as $(I pretty) argument.
string toPrettyString()
{
return toJSON(&this, true);
}
}
/**
Parses a serialized string and returns a tree of JSON values.
*/
JSONValue parseJSON(T)(T json, int maxDepth = -1) if(isInputRange!T)
{
JSONValue root = void;
root.type_tag = JSON_TYPE.NULL;
if(json.empty) return root;
int depth = -1;
dchar next = 0;
int line = 1, pos = 1;
void error(string msg)
{
throw new JSONException(msg, line, pos);
}
dchar peekChar()
{
if(!next)
{
if(json.empty) return '\0';
next = json.front;
json.popFront();
}
return next;
}
void skipWhitespace()
{
while(isWhite(peekChar())) next = 0;
}
dchar getChar(bool SkipWhitespace = false)()
{
static if(SkipWhitespace) skipWhitespace();
dchar c = void;
if(next)
{
c = next;
next = 0;
}
else
{
if(json.empty) error("Unexpected end of data.");
c = json.front;
json.popFront();
}
if(c == '\n' || (c == '\r' && peekChar() != '\n'))
{
line++;
pos = 1;
}
else
{
pos++;
}
return c;
}
void checkChar(bool SkipWhitespace = true, bool CaseSensitive = true)(char c)
{
static if(SkipWhitespace) skipWhitespace();
auto c2 = getChar();
static if(!CaseSensitive) c2 = toLower(c2);
if(c2 != c) error(text("Found '", c2, "' when expecting '", c, "'."));
}
bool testChar(bool SkipWhitespace = true, bool CaseSensitive = true)(char c)
{
static if(SkipWhitespace) skipWhitespace();
auto c2 = peekChar();
static if (!CaseSensitive) c2 = toLower(c2);
if(c2 != c) return false;
getChar();
return true;
}
string parseString()
{
auto str = appender!string();
Next:
switch(peekChar())
{
case '"':
getChar();
break;
case '\\':
getChar();
auto c = getChar();
switch(c)
{
case '"': str.put('"'); break;
case '\\': str.put('\\'); break;
case '/': str.put('/'); break;
case 'b': str.put('\b'); break;
case 'f': str.put('\f'); break;
case 'n': str.put('\n'); break;
case 'r': str.put('\r'); break;
case 't': str.put('\t'); break;
case 'u':
dchar val = 0;
foreach_reverse(i; 0 .. 4)
{
auto hex = toUpper(getChar());
if(!isHexDigit(hex)) error("Expecting hex character");
val += (isDigit(hex) ? hex - '0' : hex - ('A' - 10)) << (4 * i);
}
char[4] buf = void;
str.put(toUTF8(buf, val));
break;
default:
error(text("Invalid escape sequence '\\", c, "'."));
}
goto Next;
default:
auto c = getChar();
appendJSONChar(&str, c, &error);
goto Next;
}
return str.data ? str.data : "";
}
void parseValue(JSONValue* value)
{
depth++;
if(maxDepth != -1 && depth > maxDepth) error("Nesting too deep.");
auto c = getChar!true();
switch(c)
{
case '{':
value.type_tag = JSON_TYPE.OBJECT;
value.store.object = null;
if(testChar('}')) break;
do
{
checkChar('"');
string name = parseString();
checkChar(':');
JSONValue member = void;
parseValue(&member);
value.store.object[name] = member;
}
while(testChar(','));
checkChar('}');
break;
case '[':
value.type_tag = JSON_TYPE.ARRAY;
if(testChar(']'))
{
value.store.array = cast(JSONValue[]) "";
break;
}
value.store.array = null;
do
{
JSONValue element = void;
parseValue(&element);
value.store.array ~= element;
}
while(testChar(','));
checkChar(']');
break;
case '"':
value.type_tag = JSON_TYPE.STRING;
value.store.str = parseString();
break;
case '0': .. case '9':
case '-':
auto number = appender!string();
bool isFloat, isNegative;
void readInteger()
{
if(!isDigit(c)) error("Digit expected");
Next: number.put(c);
if(isDigit(peekChar()))
{
c = getChar();
goto Next;
}
}
if(c == '-')
{
number.put('-');
c = getChar();
isNegative = true;
}
readInteger();
if(testChar('.'))
{
isFloat = true;
number.put('.');
c = getChar();
readInteger();
}
if(testChar!(false, false)('e'))
{
isFloat = true;
number.put('e');
if(testChar('+')) number.put('+');
else if(testChar('-')) number.put('-');
c = getChar();
readInteger();
}
string data = number.data;
if(isFloat)
{
value.type_tag = JSON_TYPE.FLOAT;
value.store.floating = parse!real(data);
}
else
{
if (isNegative)
value.store.integer = parse!long(data);
else
value.store.uinteger = parse!ulong(data);
value.type_tag = !isNegative && value.store.uinteger & (1UL << 63) ? JSON_TYPE.UINTEGER : JSON_TYPE.INTEGER;
}
break;
case 't':
case 'T':
value.type_tag = JSON_TYPE.TRUE;
checkChar!(false, false)('r');
checkChar!(false, false)('u');
checkChar!(false, false)('e');
break;
case 'f':
case 'F':
value.type_tag = JSON_TYPE.FALSE;
checkChar!(false, false)('a');
checkChar!(false, false)('l');
checkChar!(false, false)('s');
checkChar!(false, false)('e');
break;
case 'n':
case 'N':
value.type_tag = JSON_TYPE.NULL;
checkChar!(false, false)('u');
checkChar!(false, false)('l');
checkChar!(false, false)('l');
break;
default:
error(text("Unexpected character '", c, "'."));
}
depth--;
}
parseValue(&root);
return root;
}
/**
Takes a tree of JSON values and returns the serialized string.
If $(D pretty) is false no whitespaces are generated.
If $(D pretty) is true serialized string is formatted to be human-readable.
No exact formatting layout is guaranteed in the latter case.
*/
string toJSON(in JSONValue* root, in bool pretty = false)
{
auto json = appender!string();
void toString(string str)
{
json.put('"');
foreach (dchar c; str)
{
switch(c)
{
case '"': json.put("\\\""); break;
case '\\': json.put("\\\\"); break;
case '/': json.put("\\/"); break;
case '\b': json.put("\\b"); break;
case '\f': json.put("\\f"); break;
case '\n': json.put("\\n"); break;
case '\r': json.put("\\r"); break;
case '\t': json.put("\\t"); break;
default:
appendJSONChar(&json, c,
(msg) { throw new JSONException(msg); });
}
}
json.put('"');
}
void toValue(in JSONValue* value, ulong indentLevel)
{
void putTabs(ulong additionalIndent = 0)
{
if(pretty)
foreach(i; 0 .. indentLevel + additionalIndent)
json.put(" ");
}
void putEOL()
{
if(pretty)
json.put('\n');
}
void putCharAndEOL(char ch)
{
json.put(ch);
putEOL();
}
final switch(value.type)
{
case JSON_TYPE.OBJECT:
if(!value.store.object.length)
{
json.put("{}");
}
else
{
putCharAndEOL('{');
bool first = true;
foreach(name, member; value.store.object)
{
if(!first)
putCharAndEOL(',');
first = false;
putTabs(1);
toString(name);
json.put(':');
if(pretty)
json.put(' ');
toValue(&member, indentLevel + 1);
}
putEOL();
putTabs();
json.put('}');
}
break;
case JSON_TYPE.ARRAY:
if(value.store.array.empty)
{
json.put("[]");
}
else
{
putCharAndEOL('[');
foreach (i, ref el; value.store.array)
{
if(i)
putCharAndEOL(',');
putTabs(1);
toValue(&el, indentLevel + 1);
}
putEOL();
putTabs();
json.put(']');
}
break;
case JSON_TYPE.STRING:
toString(value.store.str);
break;
case JSON_TYPE.INTEGER:
json.put(to!string(value.store.integer));
break;
case JSON_TYPE.UINTEGER:
json.put(to!string(value.store.uinteger));
break;
case JSON_TYPE.FLOAT:
json.put(to!string(value.store.floating));
break;
case JSON_TYPE.TRUE:
json.put("true");
break;
case JSON_TYPE.FALSE:
json.put("false");
break;
case JSON_TYPE.NULL:
json.put("null");
break;
}
}
toValue(root, 0);
return json.data;
}
private void appendJSONChar(Appender!string* dst, dchar c,
scope void delegate(string) error)
{
import std.uni : isControl;
if(isControl(c))
error("Illegal control character.");
dst.put(c);
}
/**
Exception thrown on JSON errors
*/
class JSONException : Exception
{
this(string msg, int line = 0, int pos = 0)
{
if(line)
super(text(msg, " (Line ", line, ":", pos, ")"));
else
super(msg);
}
this(string msg, string file, size_t line)
{
super(msg, file, line);
}
}
unittest
{
JSONValue jv = "123";
assert(jv.type == JSON_TYPE.STRING);
assertNotThrown(jv.str);
assertThrown!JSONException(jv.integer);
assertThrown!JSONException(jv.uinteger);
assertThrown!JSONException(jv.floating);
assertThrown!JSONException(jv.object);
assertThrown!JSONException(jv.array);
assertThrown!JSONException(jv["aa"]);
assertThrown!JSONException(jv[2]);
jv = -3;
assert(jv.type == JSON_TYPE.INTEGER);
assertNotThrown(jv.integer);
jv = cast(uint)3;
assert(jv.type == JSON_TYPE.UINTEGER);
assertNotThrown(jv.uinteger);
jv = 3.0f;
assert(jv.type == JSON_TYPE.FLOAT);
assertNotThrown(jv.floating);
jv = ["key" : "value"];
assert(jv.type == JSON_TYPE.OBJECT);
assertNotThrown(jv.object);
assertNotThrown(jv["key"]);
foreach(string key, value; jv)
{
static assert(is(typeof(value) == JSONValue));
assert(key == "key");
assert(value.type == JSON_TYPE.STRING);
assertNotThrown(value.str);
assert(value.str == "value");
}
jv = [3, 4, 5];
assert(jv.type == JSON_TYPE.ARRAY);
assertNotThrown(jv.array);
assertNotThrown(jv[2]);
foreach(size_t index, value; jv)
{
static assert(is(typeof(value) == JSONValue));
assert(value.type == JSON_TYPE.INTEGER);
assertNotThrown(value.integer);
assert(index == (value.integer-3));
}
jv = JSONValue("value");
assert(jv.type == JSON_TYPE.STRING);
assert(jv.str == "value");
JSONValue jv2 = JSONValue("value");
assert(jv2.type == JSON_TYPE.STRING);
assert(jv2.str == "value");
}
unittest
{
// Bugzilla 11504
JSONValue jv = 1;
assert(jv.type == JSON_TYPE.INTEGER);
jv.str = "123";
assert(jv.type == JSON_TYPE.STRING);
assert(jv.str == "123");
jv.integer = 1;
assert(jv.type == JSON_TYPE.INTEGER);
assert(jv.integer == 1);
jv.uinteger = 2u;
assert(jv.type == JSON_TYPE.UINTEGER);
assert(jv.uinteger == 2u);
jv.floating = 1.5f;
assert(jv.type == JSON_TYPE.FLOAT);
assert(jv.floating == 1.5f);
jv.object = ["key" : JSONValue("value")];
assert(jv.type == JSON_TYPE.OBJECT);
assert(jv.object == ["key" : JSONValue("value")]);
jv.array = [JSONValue(1), JSONValue(2), JSONValue(3)];
assert(jv.type == JSON_TYPE.ARRAY);
assert(jv.array == [JSONValue(1), JSONValue(2), JSONValue(3)]);
jv = true;
assert(jv.type == JSON_TYPE.TRUE);
jv = false;
assert(jv.type == JSON_TYPE.FALSE);
enum E{True = true}
jv = E.True;
assert(jv.type == JSON_TYPE.TRUE);
}
unittest
{
// Adding new json element via array() / object() directly
JSONValue jarr = JSONValue([10]);
foreach (i; 0..9)
jarr.array ~= JSONValue(i);
assert(jarr.array.length == 10);
JSONValue jobj = JSONValue(["key" : JSONValue("value")]);
foreach (i; 0..9)
jobj.object[text("key", i)] = JSONValue(text("value", i));
assert(jobj.object.length == 10);
}
unittest
{
// An overly simple test suite, if it can parse a serializated string and
// then use the resulting values tree to generate an identical
// serialization, both the decoder and encoder works.
auto jsons = [
`null`,
`true`,
`false`,
`0`,
`123`,
`-4321`,
`0.23`,
`-0.23`,
`""`,
`"hello\nworld"`,
`"\"\\\/\b\f\n\r\t"`,
`[]`,
`[12,"foo",true,false]`,
`{}`,
`{"a":1,"b":null}`,
// Currently broken
// `{"hello":{"json":"is great","array":[12,null,{}]},"goodbye":[true,"or",false,["test",42,{"nested":{"a":23.54,"b":0.0012}}]]}`
];
version (MinGW)
jsons ~= `1.223e+024`;
else
jsons ~= `1.223e+24`;
JSONValue val;
string result;
foreach(json; jsons)
{
try
{
val = parseJSON(json);
result = toJSON(&val);
assert(result == json, text(result, " should be ", json));
}
catch(JSONException e)
{
import std.stdio;
writefln(text(json, "\n", e.toString()));
}
}
// Should be able to correctly interpret unicode entities
val = parseJSON(`"\u003C\u003E"`);
assert(toJSON(&val) == "\"\<\>\"");
assert(val.to!string() == "\"\<\>\"");
val = parseJSON(`"\u0391\u0392\u0393"`);
assert(toJSON(&val) == "\"\Α\Β\Γ\"");
assert(val.to!string() == "\"\Α\Β\Γ\"");
val = parseJSON(`"\u2660\u2666"`);
assert(toJSON(&val) == "\"\♠\♦\"");
assert(val.to!string() == "\"\♠\♦\"");
//0x7F is a control character (see Unicode spec)
assertThrown(parseJSON(`{ "foo": "` ~ "\u007F" ~ `"}`));
with(parseJSON(`""`))
assert(str == "" && str !is null);
with(parseJSON(`[]`))
assert(!array.length && array !is null);
// Formatting
val = parseJSON(`{"a":[null,{"x":1},{},[]]}`);
assert(toJSON(&val, true) == `{
"a": [
null,
{
"x": 1
},
{},
[]
]
}`);
}
unittest
{
// Bugzilla 12332
JSONValue jv;
jv.type = JSON_TYPE.INTEGER;
jv = 1;
assert(jv.type == JSON_TYPE.INTEGER);
assert(jv.integer == 1);
jv.type = JSON_TYPE.UINTEGER;
assert(jv.uinteger == 1);
jv.type = JSON_TYPE.STRING;
assertThrown!JSONException(jv.integer == 1);
assert(jv.str is null);
jv.str = "123";
assert(jv.str == "123");
jv.type = JSON_TYPE.STRING;
assert(jv.str == "123");
jv.type = JSON_TYPE.TRUE;
assert(jv.type == JSON_TYPE.TRUE);
}
|