1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406
|
// Written in the D programming language.
/**
JavaScript Object Notation
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 http://seriot.ch/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
specialFloatLiterals = 0x1, /// encode NaN and Inf float values as strings
escapeNonAsciiChars = 0x2, /// encode non ascii characters with an unicode escape sequence
doNotEscapeSlashes = 0x4, /// do not escape slashes ('/')
strictParsing = 0x8, /// Strictly follow RFC-8259 grammar when parsing
}
/**
JSON type enumeration
*/
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;
union Store
{
string str;
long integer;
ulong uinteger;
double floating;
JSONValue[string] 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 `JSONType.object`.
* Throws: `JSONException` for read access if `type` is not
* `JSONType.object`.
* 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");
return store.object;
}
/// ditto
@property JSONValue[string] object(return scope JSONValue[string] v) pure nothrow @nogc @trusted // TODO make @safe
{
assign(v);
return v;
}
/***
* Value getter for `JSONType.object`.
* Unlike `object`, this retrieves the object by value and can be used in @safe code.
*
* A 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");
return store.object;
}
/***
* 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.
*
* A 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_;
}
/***
* Generic type value getter
* A convenience getter that returns this `JSONValue` as the specified D type.
* Note: only numeric, `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 = t; }();
}
else
{
JSONValue[string] aa;
foreach (key, value; arg)
aa[key] = JSONValue(value);
() @trusted { store.object = aa; }();
}
}
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);
}
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" );
}
/***
* Operator sets `value` for element of JSON object by `key`.
*
* If JSON value is null, then operator initializes it with object and then
* sets `value` for it.
*
* 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");
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" );
}
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;
}
/**
* Support for the `in` operator.
*
* Tests wether 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");
}
bool opEquals(const JSONValue rhs) const @nogc nothrow pure @safe
{
return opEquals(rhs);
}
bool opEquals(ref const JSONValue rhs) const @nogc nothrow pure @trusted
{
// 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)
{
case JSONType.integer:
return store.uinteger == rhs.store.integer;
case JSONType.uinteger:
return store.uinteger == rhs.store.uinteger;
case JSONType.float_:
return store.uinteger == rhs.store.floating;
default:
return false;
}
case JSONType.float_:
switch (rhs.type_tag)
{
case JSONType.integer:
return store.floating == rhs.store.integer;
case JSONType.uinteger:
return store.floating == rhs.store.uinteger;
case JSONType.float_:
return store.floating == rhs.store.floating;
default:
return false;
}
case JSONType.string:
return type_tag == rhs.type_tag && store.str == rhs.store.str;
case JSONType.object:
return type_tag == rhs.type_tag && store.object == rhs.store.object;
case JSONType.array:
return type_tag == rhs.type_tag && store.array == rhs.store.array;
case JSONType.true_:
case JSONType.false_:
case JSONType.null_:
return type_tag == rhs.type_tag;
}
}
///
@safe unittest
{
assert(JSONValue(0u) == JSONValue(0));
assert(JSONValue(0u) == JSONValue(0.0));
assert(JSONValue(0) == JSONValue(0.0));
}
/// Implements the foreach `opApply` interface for json arrays.
int opApply(scope int delegate(size_t index, ref JSONValue) dg) @system
{
int result;
foreach (size_t index, ref value; array)
{
result = dg(index, value);
if (result)
break;
}
return result;
}
/// Implements the foreach `opApply` interface for json objects.
int opApply(scope int delegate(string key, ref JSONValue) dg) @system
{
enforce!JSONException(type == JSONType.object,
"JSONValue is not an object");
int result;
foreach (string key, ref value; object)
{
result = dg(key, value);
if (result)
break;
}
return result;
}
/***
* Implicitly calls `toJSON` on this JSONValue.
*
* $(I options) can be used to tweak the conversion behavior.
*/
string toString(in JSONOptions options = JSONOptions.none) const @safe
{
return toJSON(this, false, options);
}
///
void toString(Out)(Out sink, in JSONOptions options = JSONOptions.none) const
{
toJSON(sink, this, false, options);
}
/***
* Implicitly calls `toJSON` on this JSONValue, like `toString`, but
* also passes $(I true) as $(I pretty) argument.
*
* $(I options) can be used to tweak the conversion behavior
*/
string toPrettyString(in JSONOptions options = JSONOptions.none) const @safe
{
return toJSON(this, true, options);
}
///
void toPrettyString(Out)(Out sink, in JSONOptions options = JSONOptions.none) const
{
toJSON(sink, this, true, options);
}
}
// https://issues.dlang.org/show_bug.cgi?id=20874
@system unittest
{
static struct MyCustomType
{
public string toString () const @system { return null; }
alias toString this;
}
static struct B
{
public JSONValue asJSON() const @system { return JSONValue.init; }
alias asJSON this;
}
if (false) // Just checking attributes
{
JSONValue json;
MyCustomType ilovedlang;
json = ilovedlang;
json["foo"] = ilovedlang;
auto s = ilovedlang in json;
B b;
json ~= b;
json ~ b;
}
}
/**
Parses a serialized string and returns a tree of JSON values.
Throws: $(LREF JSONException) if string does not follow the JSON grammar or the depth exceeds the max depth,
$(LREF ConvException) if a number in the input cannot be represented by a native D type.
Params:
json = json-formatted string to parse
maxDepth = maximum depth of nesting allowed, -1 disables depth checking
options = enable decoding string representations of NaN/Inf as float values
*/
JSONValue parseJSON(T)(T json, int maxDepth = -1, JSONOptions options = JSONOptions.none)
if (isSomeFiniteCharInputRange!T)
{
import std.ascii : isDigit, isHexDigit, toUpper, toLower;
import std.typecons : Nullable, Yes;
JSONValue root;
root.type_tag = JSONType.null_;
// Avoid UTF decoding when possible, as it is unnecessary when
// processing JSON.
static if (is(T : const(char)[]))
alias Char = char;
else
alias Char = Unqual!(ElementType!T);
int depth = -1;
Nullable!Char next;
int line = 1, pos = 0;
immutable bool strict = (options & JSONOptions.strictParsing) != 0;
void error(string msg)
{
throw new JSONException(msg, line, pos);
}
if (json.empty)
{
if (strict)
{
error("Empty JSON body");
}
return root;
}
bool isWhite(dchar c)
{
if (strict)
{
// RFC 7159 has a stricter definition of whitespace than general ASCII.
return c == ' ' || c == '\t' || c == '\n' || c == '\r';
}
import std.ascii : isWhite;
// Accept ASCII NUL as whitespace in non-strict mode.
return c == 0 || isWhite(c);
}
Char popChar()
{
if (json.empty) error("Unexpected end of data.");
static if (is(T : const(char)[]))
{
Char c = json[0];
json = json[1..$];
}
else
{
Char c = json.front;
json.popFront();
}
if (c == '\n')
{
line++;
pos = 0;
}
else
{
pos++;
}
return c;
}
Char peekChar()
{
if (next.isNull)
{
if (json.empty) return '\0';
next = popChar();
}
return next.get;
}
Nullable!Char peekCharNullable()
{
if (next.isNull && !json.empty)
{
next = popChar();
}
return next;
}
void skipWhitespace()
{
while (true)
{
auto c = peekCharNullable();
if (c.isNull ||
!isWhite(c.get))
{
return;
}
next.nullify();
}
}
Char getChar(bool SkipWhitespace = false)()
{
static if (SkipWhitespace) skipWhitespace();
Char c;
if (!next.isNull)
{
c = next.get;
next.nullify();
}
else
c = popChar();
return c;
}
void checkChar(bool SkipWhitespace = true)(char c, bool caseSensitive = true)
{
static if (SkipWhitespace) skipWhitespace();
auto c2 = getChar();
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;
}
wchar parseWChar()
{
wchar 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);
}
return val;
}
string parseString()
{
import std.uni : isSurrogateHi, isSurrogateLo;
import std.utf : encode, decode;
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':
wchar wc = parseWChar();
dchar val;
// Non-BMP characters are escaped as a pair of
// UTF-16 surrogate characters (see RFC 4627).
if (isSurrogateHi(wc))
{
wchar[2] pair;
pair[0] = wc;
if (getChar() != '\\') error("Expected escaped low surrogate after escaped high surrogate");
if (getChar() != 'u') error("Expected escaped low surrogate after escaped high surrogate");
pair[1] = parseWChar();
size_t index = 0;
val = decode(pair[], index);
if (index != 2) error("Invalid escaped surrogate pair");
}
else
if (isSurrogateLo(wc))
error(text("Unexpected low surrogate"));
else
val = wc;
char[4] buf;
immutable len = encode!(Yes.useReplacementDchar)(buf, val);
str.put(buf[0 .. len]);
break;
default:
error(text("Invalid escape sequence '\\", c, "'."));
}
goto Next;
default:
// RFC 7159 states that control characters U+0000 through
// U+001F must not appear unescaped in a JSON string.
// Note: std.ascii.isControl can't be used for this test
// because it considers ASCII DEL (0x7f) to be a control
// character but RFC 7159 does not.
// Accept unescaped ASCII NULs in non-strict mode.
auto c = getChar();
if (c < 0x20 && (strict || c != 0))
error("Illegal control character.");
str.put(c);
goto Next;
}
return str.data.length ? str.data : "";
}
bool tryGetSpecialFloat(string str, out double val) {
switch (str)
{
case JSONFloatLiteral.nan:
val = double.nan;
return true;
case JSONFloatLiteral.inf:
val = double.infinity;
return true;
case JSONFloatLiteral.negativeInf:
val = -double.infinity;
return true;
default:
return false;
}
}
void parseValue(ref JSONValue value)
{
depth++;
if (maxDepth != -1 && depth > maxDepth) error("Nesting too deep.");
auto c = getChar!true();
switch (c)
{
case '{':
if (testChar('}'))
{
value.object = null;
break;
}
JSONValue[string] obj;
do
{
skipWhitespace();
if (!strict && peekChar() == '}')
{
break;
}
checkChar('"');
string name = parseString();
checkChar(':');
JSONValue member;
parseValue(member);
obj[name] = member;
}
while (testChar(','));
value.object = obj;
checkChar('}');
break;
case '[':
if (testChar(']'))
{
value.type_tag = JSONType.array;
break;
}
JSONValue[] arr;
do
{
skipWhitespace();
if (!strict && peekChar() == ']')
{
break;
}
JSONValue element;
parseValue(element);
arr ~= element;
}
while (testChar(','));
checkChar(']');
value.array = arr;
break;
case '"':
auto str = parseString();
// if special float parsing is enabled, check if string represents NaN/Inf
if ((options & JSONOptions.specialFloatLiterals) &&
tryGetSpecialFloat(str, value.store.floating))
{
// found a special float, its value was placed in value.store.floating
value.type_tag = JSONType.float_;
break;
}
value.assign(str);
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;
}
if (strict && c == '0')
{
number.put('0');
if (isDigit(peekChar()))
{
error("Additional digits not allowed after initial zero digit");
}
}
else
{
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 = JSONType.float_;
value.store.floating = parse!double(data);
}
else
{
if (isNegative)
{
value.store.integer = parse!long(data);
value.type_tag = JSONType.integer;
}
else
{
// only set the correct union member to not confuse CTFE
ulong u = parse!ulong(data);
if (u & (1UL << 63))
{
value.store.uinteger = u;
value.type_tag = JSONType.uinteger;
}
else
{
value.store.integer = u;
value.type_tag = JSONType.integer;
}
}
}
break;
case 'T':
if (strict) goto default;
goto case;
case 't':
value.type_tag = JSONType.true_;
checkChar!false('r', strict);
checkChar!false('u', strict);
checkChar!false('e', strict);
break;
case 'F':
if (strict) goto default;
goto case;
case 'f':
value.type_tag = JSONType.false_;
checkChar!false('a', strict);
checkChar!false('l', strict);
checkChar!false('s', strict);
checkChar!false('e', strict);
break;
case 'N':
if (strict) goto default;
goto case;
case 'n':
value.type_tag = JSONType.null_;
checkChar!false('u', strict);
checkChar!false('l', strict);
checkChar!false('l', strict);
break;
default:
error(text("Unexpected character '", c, "'."));
}
depth--;
}
parseValue(root);
if (strict)
{
skipWhitespace();
if (!peekCharNullable().isNull) error("Trailing non-whitespace characters");
}
return root;
}
@safe unittest
{
enum issue15742objectOfObject = `{ "key1": { "key2": 1 }}`;
static assert(parseJSON(issue15742objectOfObject).type == JSONType.object);
enum issue15742arrayOfArray = `[[1]]`;
static assert(parseJSON(issue15742arrayOfArray).type == JSONType.array);
}
@safe unittest
{
// Ensure we can parse and use JSON from @safe code
auto a = `{ "key1": { "key2": 1 }}`.parseJSON;
assert(a["key1"]["key2"].integer == 1);
assert(a.toString == `{"key1":{"key2":1}}`);
}
@system unittest
{
// Ensure we can parse JSON from a @system range.
struct Range
{
string s;
size_t index;
@system
{
bool empty() { return index >= s.length; }
void popFront() { index++; }
char front() { return s[index]; }
}
}
auto s = Range(`{ "key1": { "key2": 1 }}`);
auto json = parseJSON(s);
assert(json["key1"]["key2"].integer == 1);
}
// https://issues.dlang.org/show_bug.cgi?id=20527
@safe unittest
{
static assert(parseJSON(`{"a" : 2}`)["a"].integer == 2);
}
/**
Parses a serialized string and returns a tree of JSON values.
Throws: $(LREF JSONException) if the depth exceeds the max depth.
Params:
json = json-formatted string to parse
options = enable decoding string representations of NaN/Inf as float values
*/
JSONValue parseJSON(T)(T json, JSONOptions options)
if (isSomeFiniteCharInputRange!T)
{
return parseJSON!T(json, -1, options);
}
/**
Takes a tree of JSON values and returns the serialized string.
Any Object types will be serialized in a key-sorted order.
If `pretty` is false no whitespaces are generated.
If `pretty` is true serialized string is formatted to be human-readable.
Set the $(LREF JSONOptions.specialFloatLiterals) flag is set in `options` to encode NaN/Infinity as strings.
*/
string toJSON(const ref JSONValue root, in bool pretty = false, in JSONOptions options = JSONOptions.none) @safe
{
auto json = appender!string();
toJSON(json, root, pretty, options);
return json.data;
}
///
void toJSON(Out)(
auto ref Out json,
const ref JSONValue root,
in bool pretty = false,
in JSONOptions options = JSONOptions.none)
if (isOutputRange!(Out,char))
{
void toStringImpl(Char)(string str)
{
json.put('"');
foreach (Char c; str)
{
switch (c)
{
case '"': json.put("\\\""); break;
case '\\': json.put("\\\\"); break;
case '/':
if (!(options & JSONOptions.doNotEscapeSlashes))
json.put('\\');
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:
{
import std.ascii : isControl;
import std.utf : encode;
// Make sure we do UTF decoding iff we want to
// escape Unicode characters.
assert(((options & JSONOptions.escapeNonAsciiChars) != 0)
== is(Char == dchar), "JSONOptions.escapeNonAsciiChars needs dchar strings");
with (JSONOptions) if (isControl(c) ||
((options & escapeNonAsciiChars) >= escapeNonAsciiChars && c >= 0x80))
{
// Ensure non-BMP characters are encoded as a pair
// of UTF-16 surrogate characters, as per RFC 4627.
wchar[2] wchars; // 1 or 2 UTF-16 code units
size_t wNum = encode(wchars, c); // number of UTF-16 code units
foreach (wc; wchars[0 .. wNum])
{
json.put("\\u");
foreach_reverse (i; 0 .. 4)
{
char ch = (wc >>> (4 * i)) & 0x0f;
ch += ch < 10 ? '0' : 'A' - 10;
json.put(ch);
}
}
}
else
{
json.put(c);
}
}
}
}
json.put('"');
}
void toString(string str)
{
// Avoid UTF decoding when possible, as it is unnecessary when
// processing JSON.
if (options & JSONOptions.escapeNonAsciiChars)
toStringImpl!dchar(str);
else
toStringImpl!char(str);
}
// recursive @safe inference is broken here
// workaround: if json.put is @safe, we should be too,
// so annotate the recursion as @safe manually
static if (isSafe!({ json.put(""); }))
{
void delegate(ref const JSONValue, ulong) @safe toValue;
}
else
{
void delegate(ref const JSONValue, ulong) @system toValue;
}
void toValueImpl(ref const 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 JSONType.object:
auto obj = value.objectNoRef;
if (!obj.length)
{
json.put("{}");
}
else
{
putCharAndEOL('{');
bool first = true;
void emit(R)(R names)
{
foreach (name; names)
{
auto member = obj[name];
if (!first)
putCharAndEOL(',');
first = false;
putTabs(1);
toString(name);
json.put(':');
if (pretty)
json.put(' ');
toValue(member, indentLevel + 1);
}
}
import std.algorithm.sorting : sort;
// https://issues.dlang.org/show_bug.cgi?id=14439
// auto names = obj.keys; // aa.keys can't be called in @safe code
auto names = new string[obj.length];
size_t i = 0;
foreach (k, v; obj)
{
names[i] = k;
i++;
}
sort(names);
emit(names);
putEOL();
putTabs();
json.put('}');
}
break;
case JSONType.array:
auto arr = value.arrayNoRef;
if (arr.empty)
{
json.put("[]");
}
else
{
putCharAndEOL('[');
foreach (i, el; arr)
{
if (i)
putCharAndEOL(',');
putTabs(1);
toValue(el, indentLevel + 1);
}
putEOL();
putTabs();
json.put(']');
}
break;
case JSONType.string:
toString(value.str);
break;
case JSONType.integer:
json.put(to!string(value.store.integer));
break;
case JSONType.uinteger:
json.put(to!string(value.store.uinteger));
break;
case JSONType.float_:
import std.math.traits : isNaN, isInfinity;
auto val = value.store.floating;
if (val.isNaN)
{
if (options & JSONOptions.specialFloatLiterals)
{
toString(JSONFloatLiteral.nan);
}
else
{
throw new JSONException(
"Cannot encode NaN. Consider passing the specialFloatLiterals flag.");
}
}
else if (val.isInfinity)
{
if (options & JSONOptions.specialFloatLiterals)
{
toString((val > 0) ? JSONFloatLiteral.inf : JSONFloatLiteral.negativeInf);
}
else
{
throw new JSONException(
"Cannot encode Infinity. Consider passing the specialFloatLiterals flag.");
}
}
else
{
import std.algorithm.searching : canFind;
import std.format : sformat;
// The correct formula for the number of decimal digits needed for lossless round
// trips is actually:
// ceil(log(pow(2.0, double.mant_dig - 1)) / log(10.0) + 1) == (double.dig + 2)
// Anything less will round off (1 + double.epsilon)
char[25] buf;
auto result = buf[].sformat!"%.18g"(val);
json.put(result);
if (!result.canFind('e') && !result.canFind('.'))
json.put(".0");
}
break;
case JSONType.true_:
json.put("true");
break;
case JSONType.false_:
json.put("false");
break;
case JSONType.null_:
json.put("null");
break;
}
}
toValue = &toValueImpl;
toValue(root, 0);
}
// https://issues.dlang.org/show_bug.cgi?id=12897
@safe unittest
{
JSONValue jv0 = JSONValue("test测试");
assert(toJSON(jv0, false, JSONOptions.escapeNonAsciiChars) == `"test\u6D4B\u8BD5"`);
JSONValue jv00 = JSONValue("test\u6D4B\u8BD5");
assert(toJSON(jv00, false, JSONOptions.none) == `"test测试"`);
assert(toJSON(jv0, false, JSONOptions.none) == `"test测试"`);
JSONValue jv1 = JSONValue("été");
assert(toJSON(jv1, false, JSONOptions.escapeNonAsciiChars) == `"\u00E9t\u00E9"`);
JSONValue jv11 = JSONValue("\u00E9t\u00E9");
assert(toJSON(jv11, false, JSONOptions.none) == `"été"`);
assert(toJSON(jv1, false, JSONOptions.none) == `"été"`);
}
// https://issues.dlang.org/show_bug.cgi?id=20511
@system unittest
{
import std.format.write : formattedWrite;
import std.range : nullSink, outputRangeObject;
outputRangeObject!(const(char)[])(nullSink)
.formattedWrite!"%s"(JSONValue.init);
}
// Issue 16432 - JSON incorrectly parses to string
@safe unittest
{
// Floating points numbers are rounded to the nearest integer and thus get
// incorrectly parsed
import std.math.operations : isClose;
string s = "{\"rating\": 3.0 }";
JSONValue j = parseJSON(s);
assert(j["rating"].type == JSONType.float_);
j = j.toString.parseJSON;
assert(j["rating"].type == JSONType.float_);
assert(isClose(j["rating"].floating, 3.0));
s = "{\"rating\": -3.0 }";
j = parseJSON(s);
assert(j["rating"].type == JSONType.float_);
j = j.toString.parseJSON;
assert(j["rating"].type == JSONType.float_);
assert(isClose(j["rating"].floating, -3.0));
// https://issues.dlang.org/show_bug.cgi?id=13660
auto jv1 = JSONValue(4.0);
auto textual = jv1.toString();
auto jv2 = parseJSON(textual);
assert(jv1.type == JSONType.float_);
assert(textual == "4.0");
assert(jv2.type == JSONType.float_);
}
@safe unittest
{
// Adapted from https://github.com/dlang/phobos/pull/5005
// Result from toString is not checked here, because this
// might differ (%e-like or %f-like output) depending
// on OS and compiler optimization.
import std.math.operations : isClose;
// test positive extreme values
JSONValue j;
j["rating"] = 1e18 - 65;
assert(isClose(j.toString.parseJSON["rating"].floating, 1e18 - 65));
j["rating"] = 1e18 - 64;
assert(isClose(j.toString.parseJSON["rating"].floating, 1e18 - 64));
// negative extreme values
j["rating"] = -1e18 + 65;
assert(isClose(j.toString.parseJSON["rating"].floating, -1e18 + 65));
j["rating"] = -1e18 + 64;
assert(isClose(j.toString.parseJSON["rating"].floating, -1e18 + 64));
}
/**
Exception thrown on JSON errors
*/
class JSONException : Exception
{
this(string msg, int line = 0, int pos = 0) pure nothrow @safe
{
if (line)
super(text(msg, " (Line ", line, ":", pos, ")"));
else
super(msg);
}
this(string msg, string file, size_t line) pure nothrow @safe
{
super(msg, file, line);
}
}
@system unittest
{
import std.exception;
JSONValue jv = "123";
assert(jv.type == JSONType.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 == JSONType.integer);
assertNotThrown(jv.integer);
jv = cast(uint) 3;
assert(jv.type == JSONType.uinteger);
assertNotThrown(jv.uinteger);
jv = 3.0;
assert(jv.type == JSONType.float_);
assertNotThrown(jv.floating);
jv = ["key" : "value"];
assert(jv.type == JSONType.object);
assertNotThrown(jv.object);
assertNotThrown(jv["key"]);
assert("key" in jv);
assert("notAnElement" !in jv);
assertThrown!JSONException(jv["notAnElement"]);
const cjv = jv;
assert("key" in cjv);
assertThrown!JSONException(cjv["notAnElement"]);
foreach (string key, value; jv)
{
static assert(is(typeof(value) == JSONValue));
assert(key == "key");
assert(value.type == JSONType.string);
assertNotThrown(value.str);
assert(value.str == "value");
}
jv = [3, 4, 5];
assert(jv.type == JSONType.array);
assertNotThrown(jv.array);
assertNotThrown(jv[2]);
foreach (size_t index, value; jv)
{
static assert(is(typeof(value) == JSONValue));
assert(value.type == JSONType.integer);
assertNotThrown(value.integer);
assert(index == (value.integer-3));
}
jv = null;
assert(jv.type == JSONType.null_);
assert(jv.isNull);
jv = "foo";
assert(!jv.isNull);
jv = JSONValue("value");
assert(jv.type == JSONType.string);
assert(jv.str == "value");
JSONValue jv2 = JSONValue("value");
assert(jv2.type == JSONType.string);
assert(jv2.str == "value");
JSONValue jv3 = JSONValue("\u001c");
assert(jv3.type == JSONType.string);
assert(jv3.str == "\u001C");
}
// https://issues.dlang.org/show_bug.cgi?id=11504
@system unittest
{
JSONValue jv = 1;
assert(jv.type == JSONType.integer);
jv.str = "123";
assert(jv.type == JSONType.string);
assert(jv.str == "123");
jv.integer = 1;
assert(jv.type == JSONType.integer);
assert(jv.integer == 1);
jv.uinteger = 2u;
assert(jv.type == JSONType.uinteger);
assert(jv.uinteger == 2u);
jv.floating = 1.5;
assert(jv.type == JSONType.float_);
assert(jv.floating == 1.5);
jv.object = ["key" : JSONValue("value")];
assert(jv.type == JSONType.object);
assert(jv.object == ["key" : JSONValue("value")]);
jv.array = [JSONValue(1), JSONValue(2), JSONValue(3)];
assert(jv.type == JSONType.array);
assert(jv.array == [JSONValue(1), JSONValue(2), JSONValue(3)]);
jv = true;
assert(jv.type == JSONType.true_);
jv = false;
assert(jv.type == JSONType.false_);
enum E{True = true}
jv = E.True;
assert(jv.type == JSONType.true_);
}
@system pure 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);
}
@system pure unittest
{
// Adding new json element without array() / object() access
JSONValue jarr = JSONValue([10]);
foreach (i; 0 .. 9)
jarr ~= [JSONValue(i)];
assert(jarr.array.length == 10);
JSONValue jobj = JSONValue(["key" : JSONValue("value")]);
foreach (i; 0 .. 9)
jobj[text("key", i)] = JSONValue(text("value", i));
assert(jobj.object.length == 10);
// No array alias
auto jarr2 = jarr ~ [1,2,3];
jarr2[0] = 999;
assert(jarr[0] == JSONValue(10));
}
@system unittest
{
// @system because JSONValue.array is @system
import std.exception;
// 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.25`,
`-0.25`,
`""`,
`"hello\nworld"`,
`"\"\\\/\b\f\n\r\t"`,
`[]`,
`[12,"foo",true,false]`,
`{}`,
`{"a":1,"b":null}`,
`{"goodbye":[true,"or",false,["test",42,{"nested":{"a":23.5,"b":0.140625}}]],`
~`"hello":{"array":[12,null,{}],"json":"is great"}}`,
];
enum dbl1_844 = `1.8446744073709568`;
version (MinGW)
jsons ~= dbl1_844 ~ `e+019`;
else
jsons ~= dbl1_844 ~ `e+19`;
JSONValue val;
string result;
foreach (json; jsons)
{
try
{
val = parseJSON(json);
enum pretty = false;
result = toJSON(val, pretty);
assert(result == json, text(result, " should be ", json));
}
catch (JSONException e)
{
import std.stdio : writefln;
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)
val = parseJSON(`"\u007F"`);
assert(toJSON(val) == "\"\\u007F\"");
assert(val.to!string() == "\"\\u007F\"");
with(parseJSON(`""`))
assert(str == "" && str !is null);
with(parseJSON(`[]`))
assert(!array.length);
// Formatting
val = parseJSON(`{"a":[null,{"x":1},{},[]]}`);
assert(toJSON(val, true) == `{
"a": [
null,
{
"x": 1
},
{},
[]
]
}`);
}
@safe unittest
{
auto json = `"hello\nworld"`;
const jv = parseJSON(json);
assert(jv.toString == json);
assert(jv.toPrettyString == json);
}
@system pure unittest
{
// https://issues.dlang.org/show_bug.cgi?id=12969
JSONValue jv;
jv["int"] = 123;
assert(jv.type == JSONType.object);
assert("int" in jv);
assert(jv["int"].integer == 123);
jv["array"] = [1, 2, 3, 4, 5];
assert(jv["array"].type == JSONType.array);
assert(jv["array"][2].integer == 3);
jv["str"] = "D language";
assert(jv["str"].type == JSONType.string);
assert(jv["str"].str == "D language");
jv["bool"] = false;
assert(jv["bool"].type == JSONType.false_);
assert(jv.object.length == 4);
jv = [5, 4, 3, 2, 1];
assert(jv.type == JSONType.array);
assert(jv[3].integer == 2);
}
@safe unittest
{
auto s = q"EOF
[
1,
2,
3,
potato
]
EOF";
import std.exception;
auto e = collectException!JSONException(parseJSON(s));
assert(e.msg == "Unexpected character 'p'. (Line 5:3)", e.msg);
}
// handling of special float values (NaN, Inf, -Inf)
@safe unittest
{
import std.exception : assertThrown;
import std.math.traits : isNaN, isInfinity;
// expected representations of NaN and Inf
enum {
nanString = '"' ~ JSONFloatLiteral.nan ~ '"',
infString = '"' ~ JSONFloatLiteral.inf ~ '"',
negativeInfString = '"' ~ JSONFloatLiteral.negativeInf ~ '"',
}
// with the specialFloatLiterals option, encode NaN/Inf as strings
assert(JSONValue(float.nan).toString(JSONOptions.specialFloatLiterals) == nanString);
assert(JSONValue(double.infinity).toString(JSONOptions.specialFloatLiterals) == infString);
assert(JSONValue(-real.infinity).toString(JSONOptions.specialFloatLiterals) == negativeInfString);
// without the specialFloatLiterals option, throw on encoding NaN/Inf
assertThrown!JSONException(JSONValue(float.nan).toString);
assertThrown!JSONException(JSONValue(double.infinity).toString);
assertThrown!JSONException(JSONValue(-real.infinity).toString);
// when parsing json with specialFloatLiterals option, decode special strings as floats
JSONValue jvNan = parseJSON(nanString, JSONOptions.specialFloatLiterals);
JSONValue jvInf = parseJSON(infString, JSONOptions.specialFloatLiterals);
JSONValue jvNegInf = parseJSON(negativeInfString, JSONOptions.specialFloatLiterals);
assert(jvNan.floating.isNaN);
assert(jvInf.floating.isInfinity && jvInf.floating > 0);
assert(jvNegInf.floating.isInfinity && jvNegInf.floating < 0);
// when parsing json without the specialFloatLiterals option, decode special strings as strings
jvNan = parseJSON(nanString);
jvInf = parseJSON(infString);
jvNegInf = parseJSON(negativeInfString);
assert(jvNan.str == JSONFloatLiteral.nan);
assert(jvInf.str == JSONFloatLiteral.inf);
assert(jvNegInf.str == JSONFloatLiteral.negativeInf);
}
pure nothrow @safe @nogc unittest
{
JSONValue testVal;
testVal = "test";
testVal = 10;
testVal = 10u;
testVal = 1.0;
testVal = (JSONValue[string]).init;
testVal = JSONValue[].init;
testVal = null;
assert(testVal.isNull);
}
// https://issues.dlang.org/show_bug.cgi?id=15884
pure nothrow @safe unittest
{
import std.typecons;
void Test(C)() {
C[] a = ['x'];
JSONValue testVal = a;
assert(testVal.type == JSONType.string);
testVal = a.idup;
assert(testVal.type == JSONType.string);
}
Test!char();
Test!wchar();
Test!dchar();
}
// https://issues.dlang.org/show_bug.cgi?id=15885
@safe unittest
{
enum bool realInDoublePrecision = real.mant_dig == double.mant_dig;
static bool test(const double num0)
{
import std.math.operations : feqrel;
const json0 = JSONValue(num0);
const num1 = to!double(toJSON(json0));
static if (realInDoublePrecision)
return feqrel(num1, num0) >= (double.mant_dig - 1);
else
return num1 == num0;
}
assert(test( 0.23));
assert(test(-0.23));
assert(test(1.223e+24));
assert(test(23.4));
assert(test(0.0012));
assert(test(30738.22));
assert(test(1 + double.epsilon));
assert(test(double.min_normal));
static if (realInDoublePrecision)
assert(test(-double.max / 2));
else
assert(test(-double.max));
const minSub = double.min_normal * double.epsilon;
assert(test(minSub));
assert(test(3*minSub));
}
// https://issues.dlang.org/show_bug.cgi?id=17555
@safe unittest
{
import std.exception : assertThrown;
assertThrown!JSONException(parseJSON("\"a\nb\""));
}
// https://issues.dlang.org/show_bug.cgi?id=17556
@safe unittest
{
auto v = JSONValue("\U0001D11E");
auto j = toJSON(v, false, JSONOptions.escapeNonAsciiChars);
assert(j == `"\uD834\uDD1E"`);
}
// https://issues.dlang.org/show_bug.cgi?id=5904
@safe unittest
{
string s = `"\uD834\uDD1E"`;
auto j = parseJSON(s);
assert(j.str == "\U0001D11E");
}
// https://issues.dlang.org/show_bug.cgi?id=17557
@safe unittest
{
assert(parseJSON("\"\xFF\"").str == "\xFF");
assert(parseJSON("\"\U0001D11E\"").str == "\U0001D11E");
}
// https://issues.dlang.org/show_bug.cgi?id=17553
@safe unittest
{
auto v = JSONValue("\xFF");
assert(toJSON(v) == "\"\xFF\"");
}
@safe unittest
{
import std.utf;
assert(parseJSON("\"\xFF\"".byChar).str == "\xFF");
assert(parseJSON("\"\U0001D11E\"".byChar).str == "\U0001D11E");
}
// JSONOptions.doNotEscapeSlashes (https://issues.dlang.org/show_bug.cgi?id=17587)
@safe unittest
{
assert(parseJSON(`"/"`).toString == `"\/"`);
assert(parseJSON(`"\/"`).toString == `"\/"`);
assert(parseJSON(`"/"`).toString(JSONOptions.doNotEscapeSlashes) == `"/"`);
assert(parseJSON(`"\/"`).toString(JSONOptions.doNotEscapeSlashes) == `"/"`);
}
// JSONOptions.strictParsing (https://issues.dlang.org/show_bug.cgi?id=16639)
@safe unittest
{
import std.exception : assertThrown;
// Unescaped ASCII NULs
assert(parseJSON("[\0]").type == JSONType.array);
assertThrown!JSONException(parseJSON("[\0]", JSONOptions.strictParsing));
assert(parseJSON("\"\0\"").str == "\0");
assertThrown!JSONException(parseJSON("\"\0\"", JSONOptions.strictParsing));
// Unescaped ASCII DEL (0x7f) in strings
assert(parseJSON("\"\x7f\"").str == "\x7f");
assert(parseJSON("\"\x7f\"", JSONOptions.strictParsing).str == "\x7f");
// "true", "false", "null" case sensitivity
assert(parseJSON("true").type == JSONType.true_);
assert(parseJSON("true", JSONOptions.strictParsing).type == JSONType.true_);
assert(parseJSON("True").type == JSONType.true_);
assertThrown!JSONException(parseJSON("True", JSONOptions.strictParsing));
assert(parseJSON("tRUE").type == JSONType.true_);
assertThrown!JSONException(parseJSON("tRUE", JSONOptions.strictParsing));
assert(parseJSON("false").type == JSONType.false_);
assert(parseJSON("false", JSONOptions.strictParsing).type == JSONType.false_);
assert(parseJSON("False").type == JSONType.false_);
assertThrown!JSONException(parseJSON("False", JSONOptions.strictParsing));
assert(parseJSON("fALSE").type == JSONType.false_);
assertThrown!JSONException(parseJSON("fALSE", JSONOptions.strictParsing));
assert(parseJSON("null").type == JSONType.null_);
assert(parseJSON("null", JSONOptions.strictParsing).type == JSONType.null_);
assert(parseJSON("Null").type == JSONType.null_);
assertThrown!JSONException(parseJSON("Null", JSONOptions.strictParsing));
assert(parseJSON("nULL").type == JSONType.null_);
assertThrown!JSONException(parseJSON("nULL", JSONOptions.strictParsing));
// Whitespace characters
assert(parseJSON("[\f\v]").type == JSONType.array);
assertThrown!JSONException(parseJSON("[\f\v]", JSONOptions.strictParsing));
assert(parseJSON("[ \t\r\n]").type == JSONType.array);
assert(parseJSON("[ \t\r\n]", JSONOptions.strictParsing).type == JSONType.array);
// Empty input
assert(parseJSON("").type == JSONType.null_);
assertThrown!JSONException(parseJSON("", JSONOptions.strictParsing));
// Numbers with leading '0's
assert(parseJSON("01").integer == 1);
assertThrown!JSONException(parseJSON("01", JSONOptions.strictParsing));
assert(parseJSON("-01").integer == -1);
assertThrown!JSONException(parseJSON("-01", JSONOptions.strictParsing));
assert(parseJSON("0.01").floating == 0.01);
assert(parseJSON("0.01", JSONOptions.strictParsing).floating == 0.01);
assert(parseJSON("0e1").floating == 0);
assert(parseJSON("0e1", JSONOptions.strictParsing).floating == 0);
// Trailing characters after JSON value
assert(parseJSON(`""asdf`).str == "");
assertThrown!JSONException(parseJSON(`""asdf`, JSONOptions.strictParsing));
assert(parseJSON("987\0").integer == 987);
assertThrown!JSONException(parseJSON("987\0", JSONOptions.strictParsing));
assert(parseJSON("987\0\0").integer == 987);
assertThrown!JSONException(parseJSON("987\0\0", JSONOptions.strictParsing));
assert(parseJSON("[]]").type == JSONType.array);
assertThrown!JSONException(parseJSON("[]]", JSONOptions.strictParsing));
assert(parseJSON("123 \t\r\n").integer == 123); // Trailing whitespace is OK
assert(parseJSON("123 \t\r\n", JSONOptions.strictParsing).integer == 123);
}
@system unittest
{
import std.algorithm.iteration : map;
import std.array : array;
import std.exception : assertThrown;
string s = `{ "a" : [1,2,3,], }`;
JSONValue j = parseJSON(s);
assert(j["a"].array().map!(i => i.integer()).array == [1,2,3]);
assertThrown(parseJSON(s, -1, JSONOptions.strictParsing));
}
@system unittest
{
import std.algorithm.iteration : map;
import std.array : array;
import std.exception : assertThrown;
string s = `{ "a" : { } , }`;
JSONValue j = parseJSON(s);
assert("a" in j);
auto t = j["a"].object();
assert(t.empty);
assertThrown(parseJSON(s, -1, JSONOptions.strictParsing));
}
// https://issues.dlang.org/show_bug.cgi?id=20330
@safe unittest
{
import std.array : appender;
string s = `{"a":[1,2,3]}`;
JSONValue j = parseJSON(s);
auto app = appender!string();
j.toString(app);
assert(app.data == s, app.data);
}
// https://issues.dlang.org/show_bug.cgi?id=20330
@safe unittest
{
import std.array : appender;
import std.format.write : formattedWrite;
string s =
`{
"a": [
1,
2,
3
]
}`;
JSONValue j = parseJSON(s);
auto app = appender!string();
j.toPrettyString(app);
assert(app.data == s, app.data);
}
|