File: Parse.pod

package info (click to toggle)
libjson-parse-perl 0.62-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 572 kB
  • sloc: ansic: 3,614; perl: 475; makefile: 12
file content (2643 lines) | stat: -rw-r--r-- 72,879 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643



=pod

=encoding UTF-8

=head1 NAME

JSON::Parse - Parse JSON

=head1 SYNOPSIS

    
    use JSON::Parse 'parse_json';
    my $json = '["golden", "fleece"]';
    my $perl = parse_json ($json);
    # Same effect as $perl = ['golden', 'fleece'];
    


Convert JSON into Perl.

=head1 VERSION

This documents version 0.62 of JSON::Parse corresponding to
L<git commit d04630086f6c92fea720cba4568faa0cbbdde5a6|https://github.com/benkasminbullock/JSON-Parse/commit/d04630086f6c92fea720cba4568faa0cbbdde5a6> released on Sat Jul 16 08:23:13 2022 +0900.



=head1 DESCRIPTION

A module for parsing JSON. (JSON means "JavaScript Object Notation"
and it is specified in L</RFC 8259>.)

JSON::Parse offers the function L</parse_json>, which takes a string
containing JSON, and returns an equivalent Perl structure. It also
offers validation of JSON via L</valid_json>, which returns true or
false depending on whether the JSON is correct or not, and
L</assert_valid_json>, which produces a descriptive fatal error if the
JSON is invalid. A function L</read_json> reads JSON from a
file, and there is a safer version of L</parse_json> called
L</parse_json_safe> which doesn't throw exceptions.

For special cases of parsing, there are also methods L</new> and
L</parse>, which create a JSON parsing object and run it on text. See
L</METHODS>.

JSON::Parse accepts only UTF-8 as input. See L</UTF-8 only> and
L</Handling of Unicode>.

=head1 FUNCTIONS

=head2 assert_valid_json

    
    use JSON::Parse 'assert_valid_json';
    eval {
        assert_valid_json ('["xyz":"b"]');
    };
    if ($@) {
        print "Your JSON was invalid: $@\n";
    }
    # Prints "Unexpected character ':' parsing array"


produces output

    Your JSON was invalid: JSON error at line 1, byte 7/11: Unexpected character ':' parsing array starting from byte 1: expecting whitespace: 'n', '\r', '\t', ' ' or comma: ',' or end of array: ']' at /usr/home/ben/projects/json-parse/examples/assert.pl line 6.
    


(This example is included as L<F<assert.pl>|https://fastapi.metacpan.org/source/BKB/JSON-Parse-0.62/examples/assert.pl> in the distribution.)


This is the underlying function for L</valid_json>. It runs at the
same speed, but it throws an error if the JSON is wrong, rather than
returning 1 or 0. See L</DIAGNOSTICS> for the error format, which is
identical to L</parse_json>.

This cannot detect key collisions in the JSON since it does not store
values. See L</Key collisions> for more on this module's handling of
non-unique names in the JSON.

The method equivalent to this is L</check>.

The behaviour of disallowing empty inputs was changed in version
0.49.

=head2 parse_json

    use JSON::Parse 'parse_json';
    my $perl = parse_json ('{"x":1, "y":2}');

This function converts JSON into a Perl structure, either an array
reference, a hash reference, or a scalar.

If the first argument does not contain a complete valid JSON text, is
the undefined value, an empty string, or a string containing only
whitespace C<parse_json> throws a fatal error ("dies").

If the argument contains valid JSON, the return value is either a hash
reference, an array reference, or a scalar. If the input JSON text is
a serialized object, a hash reference is returned:

    
    use JSON::Parse ':all';
    my $perl = parse_json ('{"a":1, "b":2}');
    print ref $perl, "\n";
    


produces output

    HASH


(This example is included as L<F<hash.pl>|https://fastapi.metacpan.org/source/BKB/JSON-Parse-0.62/examples/hash.pl> in the distribution.)


If the input JSON text is a serialized array, an array reference is
returned:

    
    use JSON::Parse ':all';
    my $perl = parse_json ('["a", "b", "c"]');
    print ref $perl, "\n";
    


produces output

    ARRAY


(This example is included as L<F<array.pl>|https://fastapi.metacpan.org/source/BKB/JSON-Parse-0.62/examples/array.pl> in the distribution.)


Otherwise a Perl scalar is returned. 

The behaviour of allowing a scalar was added in version 0.32 of this
module. This brings it into line with the new specification for
JSON. The behaviour of disallowing empty inputs was changed in version
0.49.

The function L</parse_json_safe> offers a version of this function
with various safety features enabled. The method L</parse> is
equivalent to this.

=head2 parse_json_safe

This is almost the same thing as L</parse_json>, but has the following
differences:

=over

=item Does not throw exceptions

If the JSON is invalid, a warning is printed and the undefined value
is returned, as if calling L</parse_json> like this:

    eval {
        $out = parse_json ($json);
    };
    if ($@) {
        carp $@;
	$out = undef;
    }

=item Detects key collisions

This switches on L</detect_collisions>, so that if the JSON contains
non-unique names, a warning is printed and the undefined value is
returned. See L</Key collisions> for an explanation of what a key
collision is.

=item Booleans are not read-only

This switches on L</copy_literals> so that JSON true, false and null
values are copied. These values can be modified, but they will not be
converted back into C<true> and C<false> by L<JSON::Create>.

=item Errors are reported by carp

Parsing errors are reported by L<Carp/carp>, so the error line number
refers to the caller's line.

=back

As the name implies, this is meant to be a "safety-first" version of
L</parse_json>. 

🎲 This function was added in version 0.38.

=head2 read_json

    use JSON::Parse 'read_json';
    my $p = read_json ('filename');

This is exactly the same as L</parse_json> except that it reads the
JSON from the specified file rather than a scalar. The file must be in
the UTF-8 encoding, and is opened as a character file using
C<:encoding(utf8)> (see L<PerlIO::encoding> and L<perluniintro>). The
output is marked as character strings.

The method equivalent is L</read>.

This is a convenience function written in Perl. You may prefer to read
the file yourself using another module if you need faster performance.

This was renamed from L</json_file_to_perl> in version 0.59. The old
name will also continue to work indefinitely.

=head2 valid_json

    use JSON::Parse 'valid_json';
    if (valid_json ($json)) {
        # do something
    }

C<valid_json> returns I<1> if its argument is valid JSON and I<0> if
not. It runs several times faster than L</parse_json>. This gain in
speed is obtained because it discards the input data after reading it,
rather than storing it into Perl variables.

This does not supply the actual errors which caused invalidity. Use
L</assert_valid_json> to get error messages when the JSON is invalid.

This cannot detect duplicate keys in JSON objects because it does not
store values. See L</Key collisions> for more on this module's
handling of non-unique names in the JSON.

=head1 METHODS

If you need to parse JSON and you are not satisfied with the parsing
options offered by L</parse_json> and L</parse_json_safe>, you can
create a JSON parsing object with L</new> and set various options on
the object, then use it with L</parse> or L</read>. 

There are options to copy JSON literals (C<true>, C<false>, C<null>)
with L</copy_literals>, switch off fatal errors with L</warn_only>,
detect duplicate keys in objects with L</detect_collisions>, set the
maximum depth of nested objects and arrays with L</set_max_depth>,
produce machine-readable parsing errors with L</diagnostics_hash>, and
set the JSON literals to user defined values with the methods
described under L</Methods for manipulating literals>.

These methods only affect the object created with L</new>; they do not
globally affect the behaviour of L</parse_json> or
L</parse_json_safe>.

=head2 check

    eval {
        $jp->check ($json);
    };

This does the same thing as L</assert_valid_json>, except its
behaviour can be modified using the L</diagnostics_hash> method.

🎲 This method was added in version 0.48. This is for the benefit of
L<JSON::Repair>.

=head2 copy_literals

    $jp->copy_literals (1);

With a true value, copy JSON literal values (C<null>, C<true>, and
C<false>) into new Perl scalar values, and don't put read-only values
into the output. 

With a false value, use read-only scalars:

    $jp->copy_literals (0);

The C<copy_literals (1)> behaviour is the behaviour of
L</parse_json_safe>. The C<copy_literals (0)> behaviour is the
behaviour of L</parse_json>.

If the user also sets user-defined literals with L</set_true>,
L</set_false> and L</set_null>, that takes precedence over this.

🎲 This method was added in version 0.38.

=head2 detect_collisions

    $jp->detect_collisions (1);

This switches on a check for hash key collisions (non-unique names in
JSON objects). If a collision is found, an error message L</Name is
not unique> is printed, which also gives the non-unique name and the
byte position where the start of the colliding string was found:

    
    use JSON::Parse;
    my $jp = JSON::Parse->new ();
    $jp->detect_collisions (1);
    eval {
        $jp->parse ('{"animals":{"cat":"moggy","cat":"feline","cat":"neko"}}');
    };
    print "$@\n" if $@;


produces output

    JSON error at line 1, byte 28/55: Name is not unique: "cat" parsing object starting from byte 12 at /usr/home/ben/projects/json-parse/examples/../blib/lib/JSON/Parse.pm line 131.
    


(This example is included as L<F<collide.pl>|https://fastapi.metacpan.org/source/BKB/JSON-Parse-0.62/examples/collide.pl> in the distribution.)


The C<detect_collisions (1)> behaviour is the behaviour of
L</parse_json_safe>. The C<detect_collisions (0)> behaviour is the
behaviour of L</parse_json>.

🎲 This method was added in version 0.38.

=head2 diagnostics_hash

    $jp->diagnostics_hash (1);

This changes diagnostics produced by errors from a simple string into
a hash reference containing various fields. This is incompatible with
L</warn_only>.

This replaces the previous experimental global variable
C<$json_diagnostics>, which was removed from the module. The hash keys
and values are identical to those provided in the object returned by
C<$json_diagnostics>, with the addition of a key C<error as string>
which returns the usual error.

This requires Perl version 5.14 or later.

An example of the use of this method to "repair" broken JSON is in the
module L</JSON::Repair>.

🎲 This method was added in version 0.46.

=head2 get_max_depth

   my $max_depth = $jp->get_max_depth ();

This returns the maximum nesting depth of objects or arrays in the
input JSON. The default value is 10,000.

🎲 This method was added in version 0.58.

=head2 new

    my $jp = JSON::Parse->new ();

Create a new JSON::Parse object.

🎲 This method was added in version 0.38.

=head2 parse

    my $out = $jp->parse ($json);

This does the same thing as L</parse_json>, except its behaviour can
be modified using object methods.

🎲 This method was added in version 0.38.

This was renamed from C<run> in version 0.60.

=head2 read

    my $json = $jp->read ($file);

Read a file, parse the contained JSON, and return the output. This
method is equivalent to the function L</read_json>.

🎲 This method was added in version 0.60.

=head2 set_max_depth

    $jp->set_max_depth (42);

Set the maximum nesting depth of objects or arrays in the input
JSON. The default value is 10,000.

🎲 This method was added in version 0.58.

=head2 upgrade_utf8

    $jp->upgrade_utf8 (1);

Upgrade input from bytes to characters automatically.

This can be switched off again using any false value:

    $jp->upgrade_utf8 (0);

🎲 This method was added in version 0.61. 

=head2 warn_only

    $jp->warn_only (1);

Warn, don't die, on error. Failed parsing returns the undefined value,
C<undef>, and prints a warning.

This can be switched off again using any false value:

    $jp->warn_only ('');

🎲 This method was added in version 0.41.

=head2 Methods for manipulating literals

These methods alter what is written into the Perl structure when the
parser sees a literal value, C<true>, C<false> or C<null> in the input
JSON.

This number of methods is needed because of the possibility that a
user wants to set the output for C<false> to be C<undef>:

    $jp->set_false (undef);

Thus, we cannot use a single function C<< $jp->false (undef) >> to
cover both setting and deleting of values.

🎲 This facility was added in version 0.38.





=head3 set_true

    $jp->set_true ("Yes, that is so true");

Supply a scalar to be used in place of the JSON C<true> literal. 

This example puts the string "Yes, that is so true" into the hash or
array when we hit a "true" literal, rather than the default read-only
scalar:

    
    use JSON::Parse;
    my $json = '{"yes":true,"no":false}';
    my $jp = JSON::Parse->new ();
    $jp->set_true ('Yes, that is so true');
    my $out = $jp->parse ($json);
    print $out->{yes}, "\n";
    


prints

    Yes, that is so true



To override the previous value, call it again with a new value. To
delete the value and revert to the default behaviour, use
L</delete_true>.



If you give this a value which is not "true", as in Perl will
evaluate it as a false in an if statement, it prints a warning
L</User-defined value for JSON true evaluates as false>.
You can switch this warning off with L</no_warn_literals>.



🎲 This method was added in version 0.38.

=head3 delete_true

    $jp->delete_true ();

Delete the user-defined true value. See L</set_true>. 

This method is "safe" in that it has absolutely no effect if no
user-defined value is in place. It does not return a value.

🎲 This method was added in version 0.38.




=head3 set_false

    $jp->set_false (JSON::PP::Boolean::false);

Supply a scalar to be used in place of the JSON C<false> literal. 

In the above example, when we hit a "false" literal, we put
C<JSON::PP::Boolean::false> in the output, similar to L<JSON::PP> and
other CPAN modules like L<Mojo::JSON> or L<JSON::XS>.


To override the previous value, call it again with a new value. To
delete the value and revert to the default behaviour, use
L</delete_false>.



If you give this a value which is not "false", as in Perl will
evaluate it as a false in an if statement, it prints a warning
L</User-defined value for JSON false evaluates as true>.
You can switch this warning off with L</no_warn_literals>.



🎲 This method was added in version 0.38.

=head3 delete_false

    $jp->delete_false ();

Delete the user-defined false value. See L</set_false>. 

This method is "safe" in that it has absolutely no effect if no
user-defined value is in place. It does not return a value.

🎲 This method was added in version 0.38.




=head3 set_null

    $jp->set_null (0);

Supply a scalar to be used in place of the JSON C<null> literal. 


To override the previous value, call it again with a new value. To
delete the value and revert to the default behaviour, use
L</delete_null>.



🎲 This method was added in version 0.38.

=head3 delete_null

    $jp->delete_null ();

Delete the user-defined null value. See L</set_null>. 

This method is "safe" in that it has absolutely no effect if no
user-defined value is in place. It does not return a value.

🎲 This method was added in version 0.38.



=head3 no_warn_literals

    $jp->no_warn_literals (1);

Use a true value to switch off warnings about setting boolean values
to contradictory things. For example if you want to set the JSON
C<false> literal to turn into the string "false",

    $jp->no_warn_literals (1);
    $jp->set_false ("false");

See also L</Contradictory values for "true" and "false">.

This also switches off the warning L</User-defined value overrules
copy_literals>.

🎲 This method was added in version 0.38.

=head1 OLD INTERFACE

The following alternative function names are accepted. These are the
names used for the functions in old versions of this module. These
names are not deprecated and will never be removed from the module.

The names ending in "_to_perl" seem quite silly in retrospect since
surely it is obvious that one is programming in Perl.

=head2 json_to_perl

This is exactly the same function as L</parse_json>.

=head2 json_file_to_perl

This is exactly the same function as L</read_json>. The function was
renamed in version 0.59, after the same function in
L</File::JSON::Slurper>.

=head2 run

This is the old name for L</parse>.

=head2 validate_json

This is exactly the same function as L</assert_valid_json>.

=head1 Mapping from JSON to Perl

JSON elements are mapped to Perl as follows:

=head2 JSON numbers

JSON numbers become Perl numbers, either integers or double-precision
floating point numbers, or possibly strings containing the number if
parsing of a number by the usual methods fails somehow.

JSON does not allow leading zeros, like I<0123>, or leading plus
signs, like I<+100>, in numbers, so these cause an L</Unexpected
character> error. JSON also does not allow numbers of the form I<1.>,
but it does allow things like I<0e0> or I<1E999999>. As far as
possible these are accepted by JSON::Parse.

=head2 JSON strings

JSON strings become Perl strings. The JSON escape characters such as
C<\t> for the tab character (see section 2.5 of L</RFC 8259>) are
mapped to the equivalent ASCII character.

=head3 Handling of Unicode

Inputs must be in the UTF-8 format. See L</UTF-8 only>.

In addition, JSON::Parse rejects UTF-8 which encodes non-characters
such as C<U+FFFF> and ill-formed characters such as incomplete halves
of surrogate pairs.

Unicode encoding points in the input of the form C<\u3000> are
converted into the equivalent UTF-8 bytes.

Surrogate pairs in the form C<\uD834\uDD1E> are also handled. If the
second half of the surrogate pair is missing, an L</Unexpected
character> or L</Unexpected end of input> error is thrown. If the
second half of the surrogate pair is present but contains an
impossible value, a L</Not surrogate pair> error is thrown.

If the input to L</parse_json> is marked as Unicode characters, the
output strings will be marked as Unicode characters. If the input is
not marked as Unicode characters, the output strings will not be
marked as Unicode characters. Thus, 

    
    use JSON::Parse ':all';
    # The scalar $sasori looks like Unicode to Perl
    use utf8;
    my $sasori = '["蠍"]';
    my $p = parse_json ($sasori);
    print utf8::is_utf8 ($p->[0]);
    # Prints 1.
    


but

    
    use JSON::Parse ':all';
    # The scalar $ebi does not look like Unicode to Perl
    no utf8;
    my $ebi = '["海老"]';
    my $p = parse_json ($ebi);
    print utf8::is_utf8 ($p->[0]);
    # Prints nothing.
    


Escapes of the form \uXXXX (see page three of L</RFC 8259>) are mapped
to ASCII if XXXX is less than 0x80, or to UTF-8 if XXXX is greater
than or equal to 0x80.

Strings containing \uXXXX escapes greater than 0x80 are also upgraded
to character strings, regardless of whether the input is a character
string or a byte string, thus regardless of whether Perl thinks the
input string is Unicode, escapes like \u87f9 are converted into the
equivalent UTF-8 bytes and the particular string in which they occur
is marked as a character string:

    
    use JSON::Parse ':all';
    no utf8;
    # 蟹
    my $kani = '["\u87f9"]';
    my $p = parse_json ($kani);
    print "It's marked as a character string" if utf8::is_utf8 ($p->[0]);
    # Prints "It's marked as a character string" because it's upgraded
    # regardless of the input string's flags.


This is modelled on the behaviour of Perl's C<chr>:

    
    no utf8;
    my $kani = '87f9';
    print "hex is character string\n" if utf8::is_utf8 ($kani);
    # prints nothing
    $kani = chr (hex ($kani));
    print "chr makes it a character string\n" if utf8::is_utf8 ($kani);
    # prints "chr makes it a character string"


However, JSON::Parse also upgrades the remaining part of the string
into a character string, even when it's not marked as a character
string. For example,

    
    use JSON::Parse ':all';
    use Unicode::UTF8 'decode_utf8';
    no utf8;
    my $highbytes = "か";
    my $not_utf8 = "$highbytes\\u3042";
    my $test = "{\"a\":\"$not_utf8\"}";
    my $out = parse_json ($test);
    # JSON::Parse does something unusual here in promoting the first part
    # of the string into UTF-8.
    print "JSON::Parse gives this: ", $out->{a}, "\n";
    # Perl cannot assume that $highbytes is in UTF-8, so it has to just
    # turn the initial characters into garbage.
    my $add_chr = $highbytes . chr (0x3042);
    print "Perl's output is like this: ", $add_chr, "\n";
    # In fact JSON::Parse's behaviour is equivalent to this:
    my $equiv = decode_utf8 ($highbytes) . chr (0x3042);
    print "JSON::Parse did something like this: ", $equiv, "\n";
    # With character strings switched on, Perl and JSON::Parse do the same
    # thing.
    use utf8;
    my $is_utf8 = "か";
    my $test2 = "{\"a\":\"$is_utf8\\u3042\"}";
    my $out2 = parse_json ($test2);
    print "JSON::Parse: ", $out2->{a}, "\n";
    my $add_chr2 = $is_utf8 . chr (0x3042);
    print "Native Perl: ", $add_chr2, "\n";


produces output

    JSON::Parse gives this: かあ
    Perl's output is like this: かあ
    JSON::Parse did something like this: かあ
    JSON::Parse: かあ
    Native Perl: かあ


(This example is included as L<F<unicode-details.pl>|https://fastapi.metacpan.org/source/BKB/JSON-Parse-0.62/examples/unicode-details.pl> in the distribution.)


Although in general the above would be an unsafe practice, JSON::Parse
can do things this way because JSON is a text-only, Unicode-only
format. To ensure that invalid inputs are never upgraded, JSON::Parse
checks each input byte to make sure that it forms UTF-8. See also
L</UTF-8 only>. Doing things this way, rather than the way that Perl
does it, was one of the original motivations for writing this
module.

=head2 JSON arrays

JSON arrays become Perl array references. The elements of the Perl
array are in the same order as they appear in the JSON.

Thus

    my $p = parse_json ('["monday", "tuesday", "wednesday"]');

has the same result as a Perl declaration of the form

    my $p = [ 'monday', 'tuesday', 'wednesday' ];

=head2 JSON objects

JSON objects become Perl hashes. The members of the JSON object become
key and value pairs in the Perl hash. The string part of each object
member becomes the key of the Perl hash. The value part of each member
is mapped to the value of the Perl hash.

Thus

    my $j = <<EOF;
    {"monday":["blue", "black"],
     "tuesday":["grey", "heart attack"],
     "friday":"Gotta get down on Friday"}
    EOF

    my $p = parse_json ($j);

has the same result as a Perl declaration of the form

    my $p = {
        monday => ['blue', 'black'],
        tuesday => ['grey', 'heart attack'],
        friday => 'Gotta get down on Friday',
    };

=head3 Key collisions

A key collision is something like the following.

    
    use JSON::Parse qw/parse_json parse_json_safe/;
    my $j = '{"a":1, "a":2}';
    my $p = parse_json ($j);
    print "Ambiguous key 'a' is ", $p->{a}, "\n";
    my $q = parse_json_safe ($j);


produces output

    JSON::Parse::parse_json_safe: Name is not unique: "a" parsing object starting from byte 1 at /usr/home/ben/projects/json-parse/examples/key-collision.pl line 8.
    Ambiguous key 'a' is 2


(This example is included as L<F<key-collision.pl>|https://fastapi.metacpan.org/source/BKB/JSON-Parse-0.62/examples/key-collision.pl> in the distribution.)


Here the key "a" could be either 1 or 2. As seen in the example,
L</parse_json> overwrites the first value with the second
value. L</parse_json_safe> halts and prints a warning. If you use
L</new> you can switch key collision on and off with the
L</detect_collisions> method.

The rationale for L</parse_json> not to give warnings is that Perl
doesn't give information about collisions when storing into hash
values, and checking for collisions for every key will degrade
performance for the sake of an unlikely occurrence. The JSON
specification says "The names within an object SHOULD be unique." (see
L</RFC 8259>, page 5), although it's not a requirement.

For performance, L</valid_json> and L</assert_valid_json> do not store
hash keys, thus they cannot detect this variety of problem.

=head2 Literals

=head3 false

L</parse_json> maps the JSON false literal to a readonly scalar which
evaluates to the empty string, or to zero in a numeric context. (This
behaviour changed from version 0.36 to 0.37. In versions up to 0.36,
the false literal was mapped to a readonly scalar which evaluated to 0
only.) L</parse_json_safe> maps the JSON literal to a similar scalar
without the readonly constraints. If you use a parser created with
L</new>, you can choose either of these behaviours with
L</copy_literals>, or you can tell JSON::Parse to put your own value
in place of falses using the L</set_false> method.

=head3 null

L</parse_json> maps the JSON null literal to a readonly scalar
C<$JSON::Parse::null> which evaluates to C<undef>. L</parse_json_safe>
maps the JSON literal to the undefined value. If you use a parser
created with L</new>, you can choose either of these behaviours with
L</copy_literals>, or you can tell JSON::Parse to put your own value
in place of nulls using the L</set_null> method.

=head3 true

L</parse_json> maps the JSON true literal to a readonly scalar which
evaluates to C<1>. L</parse_json_safe> maps the JSON literal to the
value 1. If you use a parser created with L</new>, you can choose
either of these behaviours with L</copy_literals>, or you can tell
JSON::Parse to put your own value in place of trues using the
L</set_true> method.

=head3 Round trips and compatibility

The Perl versions of literals produced by L</parse_json> will be
converted back to JSON literals if you use
L<JSON::Create/create_json>. However, JSON::Parse's literals are
incompatible with the other CPAN JSON modules. For compatibility with
other CPAN modules, create a JSON::Parse object with L</new>, and set
JSON::Parse's literals with L</set_true>, L</set_false>, and
L</set_null>.

=head3 A round trip with JSON::Tiny

This example demonstrates round-trip compatibility using L<JSON::Tiny>,
version 0.58:

    
    use utf8;
    use JSON::Tiny '0.58', qw(decode_json encode_json);
    use JSON::Parse;
    use JSON::Create;
    my $cream = '{"clapton":true,"hendrix":false}';
    my $jp = JSON::Parse->new ();
    my $jc = JSON::Create->new (sort => 1);
    
    print "First do a round-trip of our modules:\n\n";
    print $jc->create ($jp->parse ($cream)), "\n\n";
    
    print "Now do a round-trip of JSON::Tiny:\n\n";
    print encode_json (decode_json ($cream)), "\n\n";
    
    print "🥴 First, incompatible mode:\n\n";
    print 'tiny(parse): ', encode_json ($jp->parse ($cream)), "\n";
    print 'create(tiny): ', $jc->create (decode_json ($cream)), "\n\n";
    
    # Set our parser to produce these things as literals:
    $jp->set_true (JSON::Tiny::true);
    $jp->set_false (JSON::Tiny::false);
    
    print "🔄 Compatibility with JSON::Parse:\n\n";
    print 'tiny(parse):', encode_json ($jp->parse ($cream)), "\n\n";
    $jc->bool ('JSON::Tiny::_Bool');
    
    print "🔄 Compatibility with JSON::Create:\n\n";
    print 'create(tiny):', $jc->create (decode_json ($cream)), "\n\n";
    
    print "🔄 JSON::Parse and JSON::Create are still compatible too:\n\n";
    print $jc->create ($jp->parse ($cream)), "\n";


produces output

    First do a round-trip of our modules:
    
    {"clapton":true,"hendrix":false}
    
    Now do a round-trip of JSON::Tiny:
    
    {"clapton":true,"hendrix":false}
    
    🥴 First, incompatible mode:
    
    tiny(parse): {"clapton":1,"hendrix":""}
    create(tiny): {"clapton":1,"hendrix":0}
    
    🔄 Compatibility with JSON::Parse:
    
    tiny(parse):{"clapton":true,"hendrix":false}
    
    🔄 Compatibility with JSON::Create:
    
    create(tiny):{"clapton":true,"hendrix":false}
    
    🔄 JSON::Parse and JSON::Create are still compatible too:
    
    {"clapton":true,"hendrix":false}


(This example is included as L<F<json-tiny-round-trip-demo.pl>|https://fastapi.metacpan.org/source/BKB/JSON-Parse-0.62/examples/json-tiny-round-trip-demo.pl> in the distribution.)


Most of the other CPAN modules use similar methods to L<JSON::Tiny>,
so the above example can easily be adapted. See also
L<JSON::Create/Interoperability> for various examples.

=head3 Modifying the values

L</parse_json> maps all the literals to read-only values. Because of
this, attempting to modifying the boolean values in the hash reference
returned by L</parse_json> will cause "Modification of a read-only
value attempted" errors:

    my $in = '{"hocus":true,"pocus":false,"focus":null}';
    my $p = json_parse ($in);
    $p->{hocus} = 99;
    # "Modification of a read-only value attempted" error occurs

Since the hash values are read-only scalars, 
C<< $p->{hocus} = 99 >> is like this:

    undef = 99;

If you need to modify the returned hash reference, then delete the
value first:

    my $in = '{"hocus":true,"pocus":false,"focus":null}';
    my $p = json_parse ($in);
    delete $p->{pocus};
    $p->{pocus} = 99;
    # OK

Similarly with array references, delete the value before altering:

    my $in = '[true,false,null]';
    my $q = json_parse ($in);
    delete $q->[1];
    $q->[1] = 'magic';

Note that the return values from parsing bare literals are not
read-only scalars, so

    my $true = JSON::Parse::json_parse ('true');
    $true = 99;

produces no error. This is because Perl copies the scalar.

=head1 RESTRICTIONS

This module imposes the following restrictions on its input.

=over

=item JSON only

JSON::Parse is a strict parser. It only accepts input which exactly
meets the criteria of L</RFC 8259>. That means, for example,
JSON::Parse does not accept single quotes (') instead of double quotes
("), or numbers with leading zeros, like 0123. JSON::Parse does not
accept control characters (0x00 - 0x1F) in strings, missing commas
between array or hash elements like C<["a" "b"]>, or trailing commas
like C<["a","b","c",]>. It also does not accept trailing
non-whitespace, like the second "]" in C<["a"]]>. 

You may find L</JSON::Repair> by the same authors as JSON::Parse
useful if you need to process JSON-like text with tolerance for
errors.

=item No incremental parsing

JSON::Parse does not parse incrementally. It only parses fully-formed
JSON strings which include all opening and closing brackets. This is
an inherent part of the design of the module. Incremental parsing in
the style of L<XML::Parser> would require some kind of callback
structure to deal with the elements of the partially digested
structures, but JSON::Parse was never designed to do this; it merely
converts what it sees into a Perl structure. Claims to offer
incremental JSON parsing in other modules' documentation should be
diligently verified.

=item UTF-8 only

JSON::Parse only parses the UTF-8 format. If input is in a different
Unicode encoding than UTF-8, convert the input before handing it to
this module. For example, for the UTF-16 format,

    use Encode 'decode';
    my $input_utf8 = decode ('UTF-16', $input);
    my $perl = parse_json ($input_utf8);

or, for a file, use C<:encoding> (see L<PerlIO::encoding> and
L<perluniintro>):

    open my $input, "<:encoding(UTF-16)", 'some-json-file'; 

JSON::Parse does not try to determine the nature of the octet stream
using BOM markers. A BOM marker in the input consists of bytes C<0xFE>
and C<0xFF>, both of which are invalid as UTF-8, and thus will cause a
fatal error.

This restriction to UTF-8 applies regardless of whether Perl thinks
that the input string is a character string or a byte
string. Non-UTF-8 input will cause an L</Unexpected character> error.

The latest specification for JSON, L</RFC 8259>, specifies it to be a
UTF-8 only format.

JSON::Parse does not accept Unicode non-characters (U+FFFF, UFDDO,
etc.), UTF-8 representing surrogate pair code points, or bytes outside
the range of Unicode code points as UTF-8 bytes.

=back

=head1 DIAGNOSTICS

L</valid_json> does not produce error messages. L</parse_json> and
L</assert_valid_json> die on encountering invalid
input. L</parse_json_safe> uses L<Carp/carp> to pass error messages as
warnings.

Error messages have the line number, and the byte number where
appropriate, of the input which caused the problem. The line number is
formed simply by counting the number of "\n" (linefeed, ASCII 0x0A)
characters in the whitespace part of the JSON.

In L</parse_json> and L</assert_valid_json>, parsing errors are fatal,
so to continue after an error occurs, put the parsing into an C<eval>
block:

    my $p;                       
    eval {                       
        $p = parse_json ($j);  
    };                           
    if ($@) {                    
        # handle error           
    }

The following error messages are produced:

=over



=item Unexpected character

An unexpected character (byte) was encountered in the input. For
example, when looking at the beginning of a string supposedly
containing JSON, if the module encounters a plus sign, it will give an
error like this:

    assert_valid_json ('+');


gives output

    JSON error at line 1, byte 1/1: Unexpected character '+' parsing initial state: expecting whitespace: 'n', '\r', '\t', ' ' or start of string: '"' or digit: '0-9' or minus: '-' or start of an array or object: '{', '[' or start of literal: 't', 'f', 'n' 



The message always includes a list of what characters are allowed.

If there is some recognizable structure being parsed, the error
message will include its starting point in the form "starting from
byte n":

    assert_valid_json ('{"this":"\a"}');


gives output

    JSON error at line 1, byte 11/13: Unexpected character 'a' parsing string starting from byte 9: expecting escape: '', '/', '"', 'b', 'f', 'n', 'r', 't', 'u' 



A feature of JSON is that parsing it requires only one byte to be
examined at a time. Thus almost all parsing problems can be handled
using the "Unexpected character" error type, including spelling errors
in literals:

    assert_valid_json ('[true,folse]');


gives output

    JSON error at line 1, byte 8/12: Unexpected character 'o' parsing literal starting from byte 7: expecting 'a' 



and the missing second half of a surrogate pair:

    assert_valid_json ('["\udc00? <-- should be a second half here"]');


gives output

    JSON error at line 1, byte 9/44: Unexpected character '?' parsing unicode escape starting from byte 3: expecting '\' 



All kinds of errors can occur parsing numbers, for example a missing
fraction,

    assert_valid_json ('[1.e9]');


gives output

    JSON error at line 1, byte 4/6: Unexpected character 'e' parsing number starting from byte 2: expecting digit: '0-9' 



and a leading zero,

    assert_valid_json ('[0123]');


gives output

    JSON error at line 1, byte 3/6: Unexpected character '1' parsing number starting from byte 2: expecting whitespace: 'n', '\r', '\t', ' ' or comma: ',' or end of array: ']' or dot: '.' or exponential sign: 'e', 'E' 



The error message is this complicated because all of the following are
valid here: whitespace: C<[0 ]>; comma: C<[0,1]>, end of array:
C<[0]>, dot: C<[0.1]>, or exponential: C<[0e0]>.

These are all handled by this error.  Thus the error messages are a
little confusing as diagnostics.

Versions of this module prior to 0.29 gave more informative messages
like "leading zero in number". (The messages weren't documented.) The
reason to change over to the single message was because it makes the
parsing code simpler, and because the testing code described in
L</TESTING> makes use of the internals of this error to check that the
error message produced actually do correspond to the invalid and valid
bytes allowed by the parser, at the exact byte given.

This is a bytewise error, thus for example if a miscoded UTF-8 appears
in the input, an error message saying what bytes would be valid at
that point will be printed.

    
    no utf8;
    use JSON::Parse 'assert_valid_json';
    
    # Error in first byte:
    
    my $bad_utf8_1 = chr (hex ("81"));
    eval { assert_valid_json ("[\"$bad_utf8_1\"]"); };
    print "$@\n";
    
    # Error in third byte:
    
    my $bad_utf8_2 = chr (hex ('e2')) . chr (hex ('9C')) . 'b';
    eval { assert_valid_json ("[\"$bad_utf8_2\"]"); };
    print "$@\n";


prints

    JSON error at line 1, byte 3/5: Unexpected character 0x81 parsing string starting from byte 2: expecting printable ASCII or first byte of UTF-8: '\x20-\x7f', '\xC2-\xF4' at examples/bad-utf8.pl line 10.
    
    JSON error at line 1, byte 5/7: Unexpected character 'b' parsing string starting from byte 2: expecting bytes in range 80-bf: '\x80-\xbf' at examples/bad-utf8.pl line 16.
    





=item Unexpected end of input

The end of the string was encountered before the end of whatever was
being parsed was. For example, if a quote is missing from the end of
the string, it will give an error like this:

    assert_valid_json ('{"first":"Suzuki","second":"Murakami","third":"Asada}');


gives output

    JSON error at line 1: Unexpected end of input parsing string starting from byte 47 






=item Not surrogate pair

While parsing a string, a surrogate pair was encountered. While trying
to turn this into UTF-8, the second half of the surrogate pair turned
out to be an invalid value.

    assert_valid_json ('["\uDC00\uABCD"]');


gives output

    JSON error at line 1: Not surrogate pair parsing unicode escape starting from byte 11 






=item Empty input

This error occurs for an input which is an empty (no length or
whitespace only) or an undefined value.

    assert_valid_json ('');


gives output

    JSON error: Empty input parsing initial state 



Prior to version 0.49, this error was produced by
L</assert_valid_json> only, but it is now also produced by
L</parse_json>.




=item Name is not unique

This error occurs when parsing JSON when the user has chosen
L</detect_collisions>. For example an input like

    my $p = JSON::Parse->new ();
    $p->detect_collisions (1);
    $p->run ('{"hocus":1,"pocus":2,"hocus":3}');


gives output

    JSON error at line 1, byte 23/31: Name is not unique: "hocus" parsing object starting from byte 1 at blib/lib/JSON/Parse.pm line 131.



where the JSON object has two keys with the same name, C<hocus>. The
terminology "name is not unique" is from the JSON specification.




=item Contradictory values for "true" and "false"

=over

=item User-defined value for JSON false evaluates as true

This happens if you set JSON false to map to a true value:

    $jp->set_false (1);

To switch off this warning, use L</no_warn_literals>.

🎲 This warning was added in version 0.38.

=item User-defined value for JSON true evaluates as false

This happens if you set JSON true to map to a false value:

    $jp->set_true (undef);

To switch off this warning, use L</no_warn_literals>.

🎲 This warning was added in version 0.38.

=item User-defined value overrules copy_literals

This warning is given if you set up literals with L</copy_literals>
then you also set up your own true, false, or null values with
L</set_true>, L</set_false>, or L</set_null>.

🎲 This warning was added in version 0.38.

=back

=back

=head1 PERFORMANCE

On the author's computer, the module's speed of parsing is
approximately the same as L<JSON::XS>, with small variations depending
on the type of input. For validation, L</valid_json> is faster than
any other module known to the author, and up to ten times faster than
JSON::XS.

Some special types of input, such as floating point numbers containing
an exponential part, like "1e09", seem to be about two or three times
faster to parse with this module than with L<JSON::XS>. In
JSON::Parse, parsing of exponentials is done by the system's C<strtod>
function, but JSON::XS contains its own parser for exponentials, so
these results may be system-dependent. 

At the moment the main place JSON::XS wins over JSON::Parse is in
strings containing escape characters, where JSON::XS is about 10%
faster on the module author's computer and compiler. As of version
0.33, despite some progress in improving JSON::Parse, I haven't been
able to fully work out the reason behind the better speed.

There is some benchmarking code in the github repository under the
directory "benchmarks" for those wishing to test these claims. The
script L<F<benchmarks/bench>|https://github.com/benkasminbullock/JSON-Parse/d04630086f6c92fea720cba4568faa0cbbdde5a6/benchmarks/bench> is an adaptation of the similar
script in the L<JSON::XS> distribution. The script L<F<benchmarks/pub-bench.pl>|https://github.com/benkasminbullock/JSON-Parse/d04630086f6c92fea720cba4568faa0cbbdde5a6/benchmarks/pub-bench.pl> runs the benchmarks and prints them
out as POD.

The following benchmark tests used version 0.58_01 of JSON::Parse, version 4.03 of L</JSON::XS>, and version 4.25 of L</Cpanel::JSON::XS> on Perl
version v5.32.0 compiled with Clang version FreeBSD clang version 10.0.1 on FreeBSD 12.2. The files in the "benchmarks" directory
of JSON::Parse. F<short.json> and F<long.json> are the benchmarks used
by L</JSON::XS>.

=over

=item short.json

    Repetitions: 10 x 100 = 1000
    --------------+------------+------------+
    module        |      1/min |        min |
    --------------|------------|------------|
    Cpanel        | 313007.761 |  0.0000319 |
    JP::valid     | 838860.800 |  0.0000119 |
    JSON::Parse   | 310689.185 |  0.0000322 |
    JSON::XS      | 303935.072 |  0.0000329 |
    --------------+------------+------------+


=item long.json

    Repetitions: 10 x 100 = 1000
    --------------+------------+------------+
    module        |      1/min |        min |
    --------------|------------|------------|
    Cpanel        |   5611.860 |  0.0017819 |
    JP::valid     |  13586.991 |  0.0007360 |
    JSON::Parse   |   4924.048 |  0.0020308 |
    JSON::XS      |   6406.452 |  0.0015609 |
    --------------+------------+------------+


=item words-array.json

    Repetitions: 10 x 100 = 1000
    --------------+------------+------------+
    module        |      1/min |        min |
    --------------|------------|------------|
    Cpanel        |  34749.826 |  0.0002878 |
    JP::valid     | 270600.258 |  0.0000370 |
    JSON::Parse   |  34017.064 |  0.0002940 |
    JSON::XS      |  35726.610 |  0.0002799 |
    --------------+------------+------------+


=item exp.json

    Repetitions: 10 x 100 = 1000
    --------------+------------+------------+
    module        |      1/min |        min |
    --------------|------------|------------|
    Cpanel        |  46759.242 |  0.0002139 |
    JP::valid     | 117817.528 |  0.0000849 |
    JSON::Parse   |  46759.242 |  0.0002139 |
    JSON::XS      |  19195.899 |  0.0005209 |
    --------------+------------+------------+


=item literals.json

    Repetitions: 10 x 100 = 1000
    --------------+------------+------------+
    module        |      1/min |        min |
    --------------|------------|------------|
    Cpanel        |  33026.016 |  0.0003028 |
    JP::valid     | 384798.532 |  0.0000260 |
    JSON::Parse   |  40840.351 |  0.0002449 |
    JSON::XS      |  33689.189 |  0.0002968 |
    --------------+------------+------------+


=item cpantesters.json

    Repetitions: 10 x 100 = 1000
    --------------+------------+------------+
    module        |      1/min |        min |
    --------------|------------|------------|
    Cpanel        |    212.377 |  0.0470860 |
    JP::valid     |   1309.043 |  0.0076392 |
    JSON::Parse   |    207.491 |  0.0481949 |
    JSON::XS      |    226.439 |  0.0441620 |
    --------------+------------+------------+




=back

=head1 SEE ALSO

=over

=item RFC 8259

JSON is specified in L<RFC 8259 "The JavaScript Object Notation (JSON)
Data Interchange Format"|http://www.ietf.org/rfc/rfc8259.txt>.

=item json.org

L<https://json.org> is the website for JSON, authored by Douglas
Crockford.

=back

=head2 Other CPAN modules for parsing and producing JSON

 

The ⭐ represents the number of votes this module has received
on metacpan, on a logarithmic scale. Modules which we recommend are
marked with 👍. Deprecated modules and modules which are definitely
buggy (bug reports/pull requests ignored) and abandoned (no releases
for several years) are marked with 👎 and/or 🐛. Modules we can't work
out are marked with 😕.

=over

=item Modules by the same author

=over

=item JSON::Create

👍 L<JSON::Create> is a companion module to JSON::Parse by the same
author.

=item JSON::Repair

L<JSON::Repair> is an example module which demonstrates using
JSON::Parse to apply some kinds of heuristics to repair "relaxed JSON"
or otherwise broken JSON into compliant JSON.

=item JSON::Server

L<JSON::Server> is a module which offers a JSON-only, UTF-8 only
server using C<JSON::Parse> and L</JSON::Create>.

=item JSON::Tokenize

L<JSON::Tokenize> is part of the JSON::Parse distribution, a tokenizer
which reduces a JSON string to tokens. This makes the JSON::Parse
tokenizer available to people who want to write their own JSON
parsers.

=item JSON::Whitespace

L<JSON::Whitespace> is for manipulating the "insignificant whitespace"
part of JSON.

=back


=item Reading and writing JSON

=over


=item L<Cpanel::JSON::XS>


[⭐⭐ Author: L<RURBAN|https://metacpan.org/author/RURBAN>; Date: C<2021-04-12>; Version: C<4.26>]



This is a fork of L<JSON::XS>. Please see the module for details about
the reasons for the fork.


=item L<File::JSON::Slurper>


[⭐ Author: L<NEILB|https://metacpan.org/author/NEILB>; Date: C<2020-11-18>; Version: C<1.00>]



Slurp a JSON file into a data structure, and the reverse. It relies on
L</JSON::MaybeXS>.


=item L<Glib::JSON>


[⭐ Author: L<EBASSI|https://metacpan.org/author/EBASSI>; Date: C<2015-04-19>; Version: C<0.002>]



Uses the JSON library from Glib, a library of C functions for the
Linux GNOME desktop project, so it is independent of the other CPAN
modules. Judging from the fairly sparse documentation, it seems to be
a module where you build the JSON on the fly rather than converting a
Perl structure wholesale into JSON.


=item L<JSON>


[⭐⭐ Author: L<ISHIGAKI|https://metacpan.org/author/ISHIGAKI>; Date: C<2021-01-24>; Version: C<4.03>]



This calls on either L<JSON::PP> or L<JSON::XS>.


=item L<JSON::DWIW>


[Author: L<DOWENS|https://metacpan.org/author/DOWENS>; Date: C<2010-09-29>; Version: C<0.47>]



👎🐛 This module "Does What I Want", where "I" refers to the module's
author. Development seems to have ceased in 2010, there is a long list
of unfixed bugs, and some of the module's features seem to predate
Unicode support in Perl. It is written in XS, and it claims to accept
a wide variety of non-JSON formats such as comments, single-quoted
strings, trailing commas, etc.


=item L<JSON::Parser::Regexp>


[Author: L<RAJ|https://metacpan.org/author/RAJ>; Date: C<2021-03-16>; Version: C<0.04>]



Uses L<Regexp::Grammars> to parse JSON.


=item L<JSON::PP>


[⭐⭐ Author: L<ISHIGAKI|https://metacpan.org/author/ISHIGAKI>; Date: C<2021-01-23>; Version: C<4.06>]



This is part of the Perl core, installed when you install Perl. "PP"
stands for "Pure Perl", which means it is in Perl-only without the XS
(C-based) parsing. This is slower but may be necessary if you cannot
install modules requiring a C compiler.


=item L<JSON::Slurper>


[⭐ Author: L<SRCHULO|https://metacpan.org/author/SRCHULO>; Date: C<2019-10-30>; Version: C<0.12>]



Convenient file slurping and spurting of data using JSON. Uses
L</JSON::PP> or L</Cpanel::JSON::XS> if available. The basic idea
seems to be that it uses context to return arrays or hashes as
required, and read and write files without extra stages of opening and
closing the file.


=item L<JSON::Syck>


[⭐⭐ Author: L<TODDR|https://metacpan.org/author/TODDR>; Date: C<2020-10-26>; Version: C<1.34>]



👎🐛 Takes advantage of a similarity between YAML (yet another markup
language) and JSON to provide a JSON parser/producer using
L<YAML::Syck>. 

We have never tried this module, but it seems to be semi-deprecated
(the ABSTRACT says "consider using JSON::XS instead!")  and L<there
are a lot of bug reports|https://github.com/toddr/YAML-Syck/issues>
about things like failing to process equals signs. However, the
maintainer is fixing some of the bugs and making new releases, so
we're not really sure.


=item L<JSON::Tiny>


[⭐⭐ Author: L<DAVIDO|https://metacpan.org/author/DAVIDO>; Date: C<2017-11-12>; Version: C<0.58>]



This is a fork of L</Mojo::JSON>.


=item L<JSON::XS>


[⭐⭐⭐ Author: L<MLEHMANN|https://metacpan.org/author/MLEHMANN>; Date: C<2020-10-27>; Version: C<4.03>]



This is an all-purpose JSON module in XS, which means it requires a C
compiler to install.


=item L<JSON::YAJL>


[⭐ Author: L<LBROCARD|https://metacpan.org/author/LBROCARD>; Date: C<2011-08-05>; Version: C<0.10>]



👎🐛 Wraps a C library called yajl. The module has been abandoned
since ten years ago. Bug reports include serious errors, and pull
requests have been ignored.


=item L<Mojo::JSON>


[⭐⭐⭐ Author: L<SRI|https://metacpan.org/author/SRI>; Date: C<2021-04-13>; Version: C<9.17>]



Part of the L<Mojolicious> standalone web framework, "pure Perl" JSON
reader/writer. As of version 8.70 of Mojolicious, this actually
depends on L</JSON::PP> but will load L</Cpanel::JSON::XS> if it is
available.

=back

=item Combination modules

These modules rely on more than one back-end module to process JSON
for you.

=over


=item L<JSON::Any>


[⭐ Author: L<ETHER|https://metacpan.org/author/ETHER>; Date: C<2015-06-10>; Version: C<1.39>]



👎 This now-deprecated module combines L</JSON::DWIW>, L</JSON::XS>
versions one and two, and L</JSON::Syck>.


=item L<JSON::MaybeXS>


[⭐⭐ Author: L<ETHER|https://metacpan.org/author/ETHER>; Date: C<2020-11-13>; Version: C<1.004003>]



A module which combines L</Cpanel::JSON::XS>, L</JSON::XS>, and
L</JSON::PP>. The original L</JSON> combines L</JSON::XS> and
L</JSON::PP>, but this prioritizes L</Cpanel::JSON::XS> over
L</JSON::XS>.


=item L<JSON::XS::VersionOneAndTwo>


[Author: L<LBROCARD|https://metacpan.org/author/LBROCARD>; Date: C<2008-02-13>; Version: C<0.31>]



👎 A "combination module" which supports two different interfaces of
L</JSON::XS>. However, JSON::XS is now onto version 4.


=item L<Mojo::JSON::MaybeXS>


[⭐ Author: L<DBOOK|https://metacpan.org/author/DBOOK>; Date: C<2019-08-07>; Version: C<1.002>]



👎 This pulls in L</JSON::MaybeXS> instead of L</Mojo::JSON> for
L<Mojolicious> users. It seems to have been rendered obsolete by
modern versions of Mojolicious due to changes to make that depend on
L</Cpanel::JSON::XS> if available.

=back


=item Test-related modules

=over


=item L<Test2::Tools::JSON>


[Author: L<AKIYM|https://metacpan.org/author/AKIYM>; Date: C<2019-08-07>; Version: C<0.05>]




=item L<Test::Deep::JSON>


[⭐ Author: L<MOTEMEN|https://metacpan.org/author/MOTEMEN>; Date: C<2018-04-24>; Version: C<0.05>]



Compare JSON with L<Test::Deep>. As of version 0.05, it relies on
L</JSON::MaybeXS>.


=item L<Test::JSON>


[⭐ Author: L<OVID|https://metacpan.org/author/OVID>; Date: C<2009-08-09>; Version: C<0.11>]



👎 This offers a way to compare two different JSON strings to see if
they refer to the same object. The most recent version, 0.11, was
released in 2009, and it relies on the deprecated L</JSON::Any>, which
makes it essentially abandoned.


=item L<Test::JSON::Entails>


[Author: L<VOJ|https://metacpan.org/author/VOJ>; Date: C<2012-09-14>; Version: C<0.2>]



👎 Test whether one JSON or Perl structure entails/subsumes
another. The most recent version is from 2012, and it relies on
L</JSON::Any>, so it is probably abandoned. Also, oddly but not
uniquely for CPAN modules with the name JSON in the title, it seems to
not actually have that much to do with JSON, which is a data
serialisation format, but actually be testing Perl hashes and arrays.


=item L<Test::JSON::More>


[Author: L<BAYASHI|https://metacpan.org/author/BAYASHI>; Date: C<2016-04-28>; Version: C<0.02>]



JSON Test Utility. As of version 0.02, it relies on L</JSON> but it is
able to use L</JSON::XS> instead, and so probably L</Cpanel::JSON::XS>
would be OK too. According to the documentation, it can test JSON for
validity and compare JSON strings with keys in a different order, and
presumably with different whitespace.

=back

=item Type-related modules

These untangle numbers, strings, and booleans into JSON types.

=over


=item L<JSON::TypeInference>


[Author: L<AEREAL|https://metacpan.org/author/AEREAL>; Date: C<2015-10-26>; Version: C<v1.0.2>]



😕 Virtually undocumented, it's not clear what this does.


=item L<JSON::Types>


[⭐ Author: L<TYPESTER|https://metacpan.org/author/TYPESTER>; Date: C<2012-10-17>; Version: C<0.05>]



Change the type of a Perl variable so that it comes out as a number, a
string, or a boolean in the output JSON.


=item L<JSON::Types::Flexible>


[Author: L<PINE|https://metacpan.org/author/PINE>; Date: C<2017-04-01>; Version: C<0.03>]



The module is barely documented, but from looking at L<the test
file|https://metacpan.org/source/PINE/JSON-Types-Flexible-0.03/t%2Fjson%2Ftypes%2Fflexible%2Fclass.t>,
this seems to enable you to change the output type of a number or a
string so that you can, for example, make the number C<1> come out as
either a number, C<1>, a string C<"1">, or a boolean, C<true>, in the
output JSON.


=item L<JSON::Typist>


[⭐ Author: L<RJBS|https://metacpan.org/author/RJBS>; Date: C<2021-05-03>; Version: C<0.007>]



"Replace mushy strings and numbers with rigidly typed replacements"

Since Perl muddles strings and numbers, this enables you to work out
whether your input JSON was C<"123"> (a string) or C<123> (a number).

=back

=item Special-purpose modules

=over


=item L<App::JSON::to>


[⭐ Author: L<DOLMEN|https://metacpan.org/author/DOLMEN>; Date: C<2015-03-04>; Version: C<1.000>]



Convert JSON data to other formats. It reads your JSON file or input
and converts it into either YAML or Perl native format using
L<Data::Dumper>.


=item L<boolean>


[⭐⭐ Author: L<INGY|https://metacpan.org/author/INGY>; Date: C<2016-07-08>; Version: C<0.46>]



👍 This module offers C<true> and C<false> literals in Perl, so you just have

    use boolean;
    my $something = true;

This is very useful for dealing with JSON.


=item L<Config::JSON>


[Author: L<RIZEN|https://metacpan.org/author/RIZEN>; Date: C<2014-12-25>; Version: C<1.5202>]



Configuration files in JSON, with hash comments also allowed.


=item L<Devel::JSON>


[⭐ Author: L<DOLMEN|https://metacpan.org/author/DOLMEN>; Date: C<2017-09-03>; Version: C<1.001>]



For one-liners.

=over

If you use this module from the command-line, the last value of your
one-liner (-e) code will be serialized as JSON data.

=back


=item L<Inline::JSON>


[Author: L<KILNA|https://metacpan.org/author/KILNA>; Date: C<2012-07-27>; Version: C<v1.0.4>]



"Embed JSON data structures directly into your Perl code". Relies on
L</JSON>.


=item L<JSON::Builder>


[Author: L<KNI|https://metacpan.org/author/KNI>; Date: C<2015-04-16>; Version: C<0.04>]



Create JSON under memory limitations.


=item L<JSON::Color>


[⭐ Author: L<PERLANCAR|https://metacpan.org/author/PERLANCAR>; Date: C<2021-05-07>; Version: C<0.131>]



🌈 This module generates JSON colorized with ANSI escape sequences.


=item L<JSON_File>


[⭐ Author: L<GETTY|https://metacpan.org/author/GETTY>; Date: C<2014-09-11>; Version: C<0.004>]




=item L<JSON::MultiValueOrdered>


[Author: L<TOBYINK|https://metacpan.org/author/TOBYINK>; Date: C<2020-01-27>; Version: C<0.006>]



C<JSON::MultiValueOrdered> is a special-purpose module for parsing
JSON objects which have key collisions (something like
C<{"a":1,"a":2}>) within objects.

(JSON::Parse's handling of key collisions is discussed in L</Key
collisions> in this document.)


=item L<JSON::String>


[Author: L<BRUMMETT|https://metacpan.org/author/BRUMMETT>; Date: C<2015-02-04>; Version: C<v0.2.0>]



Automatically change a JSON string when a data structure changes using
tied scalars.

=back

=item Patch, path, pointer, schema, and transform modules

=over


=item L<JSON::Assert>


[Author: L<SGREEN|https://metacpan.org/author/SGREEN>; Date: C<2017-07-07>; Version: C<0.08>]



"Asserts JSONPaths into a JSON data structure for correct
values/matches"


=item L<JSON::Conditional>


[Author: L<LNATION|https://metacpan.org/author/LNATION>; Date: C<2021-03-29>; Version: C<1.00>]




=item L<JSON::GRDDL>


[Author: L<TOBYINK|https://metacpan.org/author/TOBYINK>; Date: C<2014-09-11>; Version: C<0.002>]




=item L<JSON::Hyper>


[⭐ Author: L<TOBYINK|https://metacpan.org/author/TOBYINK>; Date: C<2012-10-12>; Version: C<0.011>]




=item L<JSON::JQ>


[Author: L<DONGXU|https://metacpan.org/author/DONGXU>; Date: C<2021-05-16>; Version: C<0.06>]



Perl access to the C<jq> tool via L<Alien::LibJQ>.


=item L<JSON::MergePatch>


[⭐ Author: L<SOJIRO|https://metacpan.org/author/SOJIRO>; Date: C<2016-02-24>; Version: C<0.04>]




=item L<JSON::Patch>


[Author: L<MIXAS|https://metacpan.org/author/MIXAS>; Date: C<2018-10-25>; Version: C<0.04>]



😕 We don't know what this does, or how it relates to JSON. The example
in the synopsis section of the document doesn't show any JSON, it
shows an example of altering nested hashes in Perl.


=item L<JSON::Path>


[⭐ Author: L<POPEFELIX|https://metacpan.org/author/POPEFELIX>; Date: C<2021-01-28>; Version: C<0.431>]



Search nested hashref/arrayref structures using JSONPath.


=item L<JSON::Pointer>


[⭐ Author: L<ZIGOROU|https://metacpan.org/author/ZIGOROU>; Date: C<2015-08-13>; Version: C<0.07>]



Extract parts of a JSON string.


=item L<JSON::Schema::ToJSON>


[⭐ Author: L<LEEJO|https://metacpan.org/author/LEEJO>; Date: C<2021-04-06>; Version: C<0.19>]



"Generate example JSON structures from JSON Schema definitions"


=item L<JSON::T>


[⭐ Author: L<TOBYINK|https://metacpan.org/author/TOBYINK>; Date: C<2014-09-28>; Version: C<0.104>]



Transform JSON using JsonT


=item L<JSON::Transform>


[⭐ Author: L<ETJ|https://metacpan.org/author/ETJ>; Date: C<2020-01-01>; Version: C<0.03>]




=item L<JSON::Validator>


[⭐⭐ Author: L<JHTHORSEN|https://metacpan.org/author/JHTHORSEN>; Date: C<2021-04-28>; Version: C<4.17>]



"Validate data against a JSON schema" - you can decide what the JSON
is supposed to contain.


=item L<Template::Plugin::JSON>


[Author: L<ETHER|https://metacpan.org/author/ETHER>; Date: C<2019-03-07>; Version: C<0.08>]



"Adds a .json vmethod for all TT values." - for use with L<Template>.

=back

=item JSON extensions

These modules extend JSON with comments and other things.

=over


=item L<JSON::Diffable>


[⭐ Author: L<PHAYLON|https://metacpan.org/author/PHAYLON>; Date: C<2014-12-10>; Version: C<0.000002>]



"A relaxed and easy diffable JSON variant"


=item L<JSON::Relaxed>


[Author: L<MIKO|https://metacpan.org/author/MIKO>; Date: C<2016-04-30>; Version: C<0.05>]



"An extension of JSON that allows for better human-readability".


=item L<JSON::WithComments>


[Author: L<RJRAY|https://metacpan.org/author/RJRAY>; Date: C<2017-09-02>; Version: C<0.003>]




=item L<JSONY>


[⭐ Author: L<INGY|https://metacpan.org/author/INGY>; Date: C<2020-04-27>; Version: C<v0.1.21>]



"Relaxed JSON with a little bit of YAML"

=back

=item Web interactions via JSON

=over


=item L<Crypt::JWT>


[⭐⭐ Author: L<MIK|https://metacpan.org/author/MIK>; Date: C<2021-05-01>; Version: C<0.033>]



Module covers JSON Web Tokens, JSON Web Signature, and JSON Web
Encryption.


=item L<JSON::API>


[⭐ Author: L<GFRANKS|https://metacpan.org/author/GFRANKS>; Date: C<2019-07-01>; Version: C<v1.1.1>]



Combines L<LWP::UserAgent> and L<JSON> to make a unified module to
communicate with a web server via JSON.


=item L<LWP::JSON::Tiny>


[⭐ Author: L<SKINGTON|https://metacpan.org/author/SKINGTON>; Date: C<2018-05-11>; Version: C<0.014>]




=item L<WWW::JSON>


[⭐ Author: L<ANTIPASTA|https://metacpan.org/author/ANTIPASTA>; Date: C<2015-05-27>; Version: C<1.02>]



"Make working with JSON Web API's as painless as possible"

=back

=item Extension modules

These modules extend the existing modules with some extra bits.

=over


=item L<JSON::XS::Sugar>


[Author: L<MAXMIND|https://metacpan.org/author/MAXMIND>; Date: C<2015-04-01>; Version: C<1.01>]



Provides booleans and number/string forcing for L</JSON::XS>.


=item L<Silki::JSON>


[⭐ Author: L<DROLSKY|https://metacpan.org/author/DROLSKY>; Date: C<2011-09-19>; Version: C<0.29>]



Switches on formatting and strict utf8 in a L</JSON::XS> object.

=back

=item Demonstration modules

These modules provide a JSON parser as a demonstration of another
technology.

=over


=item L<JSON::Decode::Marpa>


[Author: L<PERLANCAR|https://metacpan.org/author/PERLANCAR>; Date: C<2014-08-27>; Version: C<0.02>]




=item L<JSON::Decode::Regexp>


[Author: L<PERLANCAR|https://metacpan.org/author/PERLANCAR>; Date: C<2018-03-25>; Version: C<0.101>]



🐛🦟🦋🐞 JSON parser as a single Perl Regex, originally by Randal
Schwartz. This may be ingenious, but it's not remotely a useful JSON
parser. For example, looking at the string part, it provides no
Unicode validation, L<no support for Unicode
escapes|https://metacpan.org/release/JSON-Decode-Regexp/source/lib/JSON/Decode/Regexp.pm#L141>
and it L<allows invalid escapes such as
C<\xFF>|https://metacpan.org/release/JSON-Decode-Regexp/source/lib/JSON/Decode/Regexp.pm#L137>.


=item L<MarpaX::Demo::JSONParser>


[Author: L<RSAVAGE|https://metacpan.org/author/RSAVAGE>; Date: C<2019-06-18>; Version: C<1.08>]




=item L<Pegex::JSON>


[Author: L<INGY|https://metacpan.org/author/INGY>; Date: C<2020-01-22>; Version: C<0.31>]



🐛 Based on L<Pegex>.  See
L<our bug report|https://github.com/pegex-parser/pegex-json-pm/issues/3>.

=back

=item Other modules

Modules which are parts of bigger distributions have not been included
here except by accident.

=over


=item L<App::JSON::Tools>


[Author: L<KABLAMO|https://metacpan.org/author/KABLAMO>; Date: C<2016-08-05>; Version: C<0.01>]



Undocumented command-line tools for JSON.


=item L<App::JSONPretty>


[⭐ Author: L<MSTROUT|https://metacpan.org/author/MSTROUT>; Date: C<2011-02-02>; Version: C<1>]



👎🐛 JSON prettification script. For whatever reason the script
encapsulates the entirety of an old version of the L</JSON> module
dating from before L</JSON::PP> was included in the Perl core.

If you need this kind of script, there is something called L<json_xs>
which comes with L</JSON::XS>, or equivalently L<cpanel_json_xs> in
the forked module L</Cpanel::JSON::XS>.


=item L<ARGV::JSON>


[⭐ Author: L<MOTEMEN|https://metacpan.org/author/MOTEMEN>; Date: C<2013-12-18>; Version: C<0.01>]




=item L<Jasonify>


[Author: L<BOBK|https://metacpan.org/author/BOBK>; Date: C<2020-03-04>; Version: C<v0.20.064>]




=item L<JS::JSON>


[Author: L<INGY|https://metacpan.org/author/INGY>; Date: C<2008-08-30>; Version: C<0.02>]



👎 This is JavaScript code which was uploaded to CPAN. The original
JavaScript is now obsolete since the thing it codes is included in all
modern web browsers.


=item L<JSON::Eval>


[Author: L<TOBYINK|https://metacpan.org/author/TOBYINK>; Date: C<2019-10-27>; Version: C<0.002>]



Eval Perl code found in JSON. This module enables one to encode and
decode Perl scalar references and code references to JSON.


=item L<JSON::ize>


[⭐ Author: L<MAJENSEN|https://metacpan.org/author/MAJENSEN>; Date: C<2019-07-13>; Version: C<0.202>]




=item L<JSON::JSend>


[Author: L<HOEKIT|https://metacpan.org/author/HOEKIT>; Date: C<2016-04-23>; Version: C<0.02>]




=item L<JSON::Lines>


[⭐ Author: L<LNATION|https://metacpan.org/author/LNATION>; Date: C<2021-03-29>; Version: C<1.00>]



"JSON Lines is a convenient format for storing structured data that
may be processed one record at a time."


=item L<JSON::Meth>


[⭐ Author: L<ZOFFIX|https://metacpan.org/author/ZOFFIX>; Date: C<2015-11-28>; Version: C<1.001007>]



😕 Claims to be "no nonsense JSON encoding/decoding as method calls on
data". From the documentation:

=over

Don't make me think and give me what I want! This module automatically
figures out whether you want to encode a Perl data structure to JSON
or decode a JSON string to a Perl data structure.

=back


=item L<JSON::ON>


[Author: L<EWILHELM|https://metacpan.org/author/EWILHELM>; Date: C<2013-06-26>; Version: C<v0.0.3>]



JavaScript object notation object notator.


=item L<JSON::SL>


[⭐ Author: L<MNUNBERG|https://metacpan.org/author/MNUNBERG>; Date: C<2017-11-10>; Version: C<v1.0.7>]




=item L<JSON::Streaming::Reader>


[⭐ Author: L<MART|https://metacpan.org/author/MART>; Date: C<2012-11-24>; Version: C<0.06>]




=item L<JSON::Streaming::Writer>


[Author: L<MART|https://metacpan.org/author/MART>; Date: C<2012-11-24>; Version: C<0.03>]




=item L<JSON::Util>


[Author: L<JKUTEJ|https://metacpan.org/author/JKUTEJ>; Date: C<2015-09-03>; Version: C<0.06>]



Relies on L<JSON::MaybeXS> and the author's other module L<IO::Any>,
so that you can put either a file name or a JSON string as the
argument and it tries to work out which one you have given it. That is
ingenious, but it seems that if you are a programmer who cannot
distinguish whether your input string is a file name or JSON, you have
a very serious problem.


=item L<JSON::XS::ByteString>


[⭐ Author: L<CINDY|https://metacpan.org/author/CINDY>; Date: C<2020-04-18>; Version: C<1.004>]



😕 L<The
README|https://metacpan.org/source/CINDY/JSON-XS-ByteString-1.004/README>
claims it is a "thin wrapper around JSON::XS", but L<it contains a
complete implementation of
JSON|https://metacpan.org/source/CINDY/JSON-XS-ByteString-1.004/ByteString.xs>,
which seems to have partly been copy-pasted from the JSON::XS source
code, but internally it doesn't make any reference to JSON::XS. The
licence and copyright statement don't mention JSON::XS's original
author at all so we're not sure if this is a fork, a wrapper, or a
reimplementation.

We haven't tried downloading this or installing it, but according to
the documentation, this module encodes numbers with quotes around
them, so C<< {this => 2} >> turns into C<{"this":"2"}>.


=item L<JSON_minify>


[Author: L<RCOSCALI|https://metacpan.org/author/RCOSCALI>; Date: C<2021-01-24>; Version: C<1.1>]




=item L<Text::JSON::Nibble>


[Author: L<DAEMON|https://metacpan.org/author/DAEMON>; Date: C<2017-05-02>; Version: C<1.01>]



Nibble complete JSON objects from buffers.

This seems to be for extracting JSON from the midst of noise.

=back

=back

=head1 SCRIPT

A script "validjson" is supplied with the module. This runs
L</assert_valid_json> on its inputs, so run it like this.

     validjson *.json

The default behaviour is to just do nothing if the input is valid. For
invalid input it prints what the problem is:

    validjson ids.go 
    ids.go: JSON error at line 1, byte 1/7588: Unexpected character '/' parsing initial state: expecting whitespace: '\n', '\r', '\t', ' ' or start of string: '"' or digit: '0-9' or minus: '-' or start of an array or object: '{', '[' or start of literal: 't', 'f', 'n'.

If you need confirmation, use its --verbose option:

    validjson -v *.json

    atoms.json is valid JSON.
    ids.json is valid JSON.
    kanjidic.json is valid JSON.
    linedecomps.json is valid JSON.
    radkfile-radicals.json is valid JSON.

=head1 DEPENDENCIES

=over

=item L<Carp>

=back

=head1 EXPORTS

The module exports nothing by default. Functions L</parse_json>,
L</parse_json_safe>, L</read_json>, L</valid_json> and
L</assert_valid_json>, as well as the old function names
L</validate_json>, L</json_file_to_perl>, and L</json_to_perl>, can be
exported on request.

All of the functions can be exported using the tag ':all':

    use JSON::Parse ':all';

=head1 TESTING

=head2 Internal testing code

The module incorporates extensive testing related to the production of
error messages and validation of input. Some of the testing code is
supplied with the module in the F</t/> subdirectory of the
distribution.

More extensive testing code is in the git repository. This is not
supplied in the CPAN distribution. A script, L<F<randomjson.pl>|https://github.com/benkasminbullock/JSON-Parse/d04630086f6c92fea720cba4568faa0cbbdde5a6/randomjson.pl>,
generates a set number of bytes of random JSON and checks that the
module's bytewise validation of input is correct. It does this by
taking a valid fragment, then adding each possible byte from 0 to 255
to see whether the module correctly identifies it as valid or invalid
at that point, then randomly picking one of the valid bytes and adding
it to the fragment and continuing the process until a complete valid
JSON input is formed. The module has undergone about a billion
repetitions of this test.

This setup relies on a C file, L<F<json-random-test.c>|https://github.com/benkasminbullock/JSON-Parse/d04630086f6c92fea720cba4568faa0cbbdde5a6/json-random-test.c>, which
isn't in the CPAN distribution, and it also requires L<F<Json3.xs>|https://github.com/benkasminbullock/JSON-Parse/d04630086f6c92fea720cba4568faa0cbbdde5a6/Json3.xs> to be edited to make the macro C<TESTRANDOM> true
(uncomment line 7 of the file). The testing code uses C
setjmp/longjmp, so it's not guaranteed to work on all operating
systems and is commented out for CPAN releases.

A pure C version called L<F<random-test.c>|https://github.com/benkasminbullock/JSON-Parse/d04630086f6c92fea720cba4568faa0cbbdde5a6/random-test.c> also exists. This applies
exactly the same tests, and requires no Perl at all.

If you're interested in testing your own JSON parser, the outputs
generated by L<F<randomjson.pl>|https://github.com/benkasminbullock/JSON-Parse/d04630086f6c92fea720cba4568faa0cbbdde5a6/randomjson.pl> are quite a good place to
start. The default is to produce UTF-8 output, which looks pretty
horrible since it tends to produce long strings of UTF-8
garbage. (This is because it chooses randomly from 256 bytes and the
end-of-string marker C<"> has only a 1/256 chance of being chosen, so
the strings tend to get long and messy). You can mess with the
internals of JSON::Parse by setting MAXBYTE in F<json-common.c> to
0x80, recompiling (you can ignore the compiler warnings), and running
F<randomjson.pl> again to get just ASCII random JSON things. This
breaks the UTF-8 functionality of JSON::Parse, so please don't install
that version.

=head2 JSON Parsing Test Suite

JSON::Parse version 0.58 passes most of the JSON Parsing Test Suite,
with the exception that JSON::Parse rejects various erroneous UTF-8
inputs, for example JSON::Parse will throw an error for non-character
code points like Unicode U+FFFF and U+10FFFF. This parser only accepts
valid UTF-8 as input. See L</UTF-8 only>. 

In our opinion it would be a disservice to users of this module to
allow bytes containing useless fragments such as incomplete parts of
surrogate pairs, or invalid characters, just because the JSON
specification doesn't actually explicitly demand rejecting these kinds
of garbage inputs. Please see the function C<daft_test> in the file
F<xt/JPXT.pm> for exactly which of these elements of the test suite we
do not comply with. We note that this comment from Douglas Crockford,
the inventor of JSON, L<JSON
parser|https://github.com/douglascrockford/JSON-c/blob/master/utf8_decode.c#L38-L43>,
dated 2005, agrees with our opinion on this point.

JSON::Parse version 0.58 also introduced L</get_max_depth> and
L</set_max_depth> to prevent the stack overflow errors caused by some
very deeply nested inputs such as those of the JSON Parsing Test
Suite.

=head1 ACKNOWLEDGEMENTS

Toby Inkster (TOBYINK) suggested some of the new function names which
replaced the L</OLD INTERFACE> names. Nicolas Immelman and Shlomi Fish
(SHLOMIF) reported memory leaks which were fixed in 0.32 and
0.40. Github user kolmogorov42 reported a bug which led to
0.42. Github user SteveGlassman found an error in string copying for
long strings, fixed in 0.57. Lars Dɪᴇᴄᴋᴏᴡ (DAXIM) pointed out problems
with the JSON Parsing Test Suite which led to the addition of stack
protection and L</set_max_depth> and L</get_max_depth> in 0.58.




=head1 AUTHOR

Ben Bullock, <bkb@cpan.org>

=head1 COPYRIGHT & LICENCE

This package and associated files are copyright (C) 
2013-2022
Ben Bullock.

You can use, copy, modify and redistribute this package and associated
files under the Perl Artistic Licence or the GNU General Public
Licence.