1JSON version 2.53 2================= 3 4JSON::PP was inculded in JSON distribution (CPAN module). 5It comes to be a perl core module in Perl 5.14. 6And JSON::PP well be split away it. 7 8This developer-versoin is for the preparation. 9 10 * JSON distribution will inculde yet another JSON::PP modules. 11 They are JSNO::backportPP. So JSON.pm should work as it did at all! 12 13================= 14 15INSTALLATION 16 17To install this module type the following: 18 19 perl Makefile.PL 20 make 21 make test 22 make install 23 24NAME 25 JSON - JSON (JavaScript Object Notation) encoder/decoder 26 27SYNOPSIS 28 use JSON; # imports encode_json, decode_json, to_json and from_json. 29 30 # simple and fast interfaces (expect/generate UTF-8) 31 32 $utf8_encoded_json_text = encode_json $perl_hash_or_arrayref; 33 $perl_hash_or_arrayref = decode_json $utf8_encoded_json_text; 34 35 # OO-interface 36 37 $json = JSON->new->allow_nonref; 38 39 $json_text = $json->encode( $perl_scalar ); 40 $perl_scalar = $json->decode( $json_text ); 41 42 $pretty_printed = $json->pretty->encode( $perl_scalar ); # pretty-printing 43 44 # If you want to use PP only support features, call with '-support_by_pp' 45 # When XS unsupported feature is enable, using PP (de|en)code instead of XS ones. 46 47 use JSON -support_by_pp; 48 49 # option-acceptable interfaces (expect/generate UNICODE by default) 50 51 $json_text = to_json( $perl_scalar, { ascii => 1, pretty => 1 } ); 52 $perl_scalar = from_json( $json_text, { utf8 => 1 } ); 53 54 # Between (en|de)code_json and (to|from)_json, if you want to write 55 # a code which communicates to an outer world (encoded in UTF-8), 56 # recommend to use (en|de)code_json. 57 58VERSION 59 2.53 60 61 This version is compatible with JSON::XS 2.27 and later. 62 63NOTE 64 JSON::PP was inculded in "JSON" distribution. It comes to be a perl core 65 module in Perl 5.14. And JSON::PP will be split away it. 66 67 "JSON" distribution will inculde yet another JSON::PP modules. They are 68 JSNO::backportPP and so on. JSON.pm should work as it did at all. 69 70DESCRIPTION 71 ************************** CAUTION ******************************** 72 * This is 'JSON module version 2' and there are many differences * 73 * to version 1.xx * 74 * Please check your applications useing old version. * 75 * See to 'INCOMPATIBLE CHANGES TO OLD VERSION' * 76 ******************************************************************* 77 78 JSON (JavaScript Object Notation) is a simple data format. See to 79 <http://www.json.org/> and 80 "RFC4627"(<http://www.ietf.org/rfc/rfc4627.txt>). 81 82 This module converts Perl data structures to JSON and vice versa using 83 either JSON::XS or JSON::PP. 84 85 JSON::XS is the fastest and most proper JSON module on CPAN which must 86 be compiled and installed in your environment. JSON::PP is a pure-Perl 87 module which is bundled in this distribution and has a strong 88 compatibility to JSON::XS. 89 90 This module try to use JSON::XS by default and fail to it, use JSON::PP 91 instead. So its features completely depend on JSON::XS or JSON::PP. 92 93 See to "BACKEND MODULE DECISION". 94 95 To distinguish the module name 'JSON' and the format type JSON, the 96 former is quoted by C<> (its results vary with your using media), and 97 the latter is left just as it is. 98 99 Module name : "JSON" 100 101 Format type : JSON 102 103 FEATURES 104 * correct unicode handling 105 106 This module (i.e. backend modules) knows how to handle Unicode, 107 documents how and when it does so, and even documents what "correct" 108 means. 109 110 Even though there are limitations, this feature is available since 111 Perl version 5.6. 112 113 JSON::XS requires Perl 5.8.2 (but works correctly in 5.8.8 or 114 later), so in older versions "JSON" sholud call JSON::PP as the 115 backend which can be used since Perl 5.005. 116 117 With Perl 5.8.x JSON::PP works, but from 5.8.0 to 5.8.2, because of 118 a Perl side problem, JSON::PP works slower in the versions. And in 119 5.005, the Unicode handling is not available. See to "UNICODE 120 HANDLING ON PERLS" in JSON::PP for more information. 121 122 See also to "A FEW NOTES ON UNICODE AND PERL" in JSON::XS and 123 "ENCODING/CODESET_FLAG_NOTES" in JSON::XS. 124 125 * round-trip integrity 126 127 When you serialise a perl data structure using only data types 128 supported by JSON and Perl, the deserialised data structure is 129 identical on the Perl level. (e.g. the string "2.0" doesn't suddenly 130 become "2" just because it looks like a number). There *are* minor 131 exceptions to this, read the "MAPPING" section below to learn about 132 those. 133 134 * strict checking of JSON correctness 135 136 There is no guessing, no generating of illegal JSON texts by 137 default, and only JSON is accepted as input by default (the latter 138 is a security feature). 139 140 See to "FEATURES" in JSON::XS and "FEATURES" in JSON::PP. 141 142 * fast 143 144 This module returns a JSON::XS object itself if available. Compared 145 to other JSON modules and other serialisers such as Storable, 146 JSON::XS usually compares favourably in terms of speed, too. 147 148 If not available, "JSON" returns a JSON::PP object instead of 149 JSON::XS and it is very slow as pure-Perl. 150 151 * simple to use 152 153 This module has both a simple functional interface as well as an 154 object oriented interface interface. 155 156 * reasonably versatile output formats 157 158 You can choose between the most compact guaranteed-single-line 159 format possible (nice for simple line-based protocols), a pure-ASCII 160 format (for when your transport is not 8-bit clean, still supports 161 the whole Unicode range), or a pretty-printed format (for when you 162 want to read that stuff). Or you can combine those features in 163 whatever way you like. 164 165FUNCTIONAL INTERFACE 166 Some documents are copied and modified from "FUNCTIONAL INTERFACE" in 167 JSON::XS. "to_json" and "from_json" are additional functions. 168 169 encode_json 170 $json_text = encode_json $perl_scalar 171 172 Converts the given Perl data structure to a UTF-8 encoded, binary 173 string. 174 175 This function call is functionally identical to: 176 177 $json_text = JSON->new->utf8->encode($perl_scalar) 178 179 decode_json 180 $perl_scalar = decode_json $json_text 181 182 The opposite of "encode_json": expects an UTF-8 (binary) string and 183 tries to parse that as an UTF-8 encoded JSON text, returning the 184 resulting reference. 185 186 This function call is functionally identical to: 187 188 $perl_scalar = JSON->new->utf8->decode($json_text) 189 190 to_json 191 $json_text = to_json($perl_scalar) 192 193 Converts the given Perl data structure to a json string. 194 195 This function call is functionally identical to: 196 197 $json_text = JSON->new->encode($perl_scalar) 198 199 Takes a hash reference as the second. 200 201 $json_text = to_json($perl_scalar, $flag_hashref) 202 203 So, 204 205 $json_text = to_json($perl_scalar, {utf8 => 1, pretty => 1}) 206 207 equivalent to: 208 209 $json_text = JSON->new->utf8(1)->pretty(1)->encode($perl_scalar) 210 211 If you want to write a modern perl code which communicates to outer 212 world, you should use "encode_json" (supposed that JSON data are encoded 213 in UTF-8). 214 215 from_json 216 $perl_scalar = from_json($json_text) 217 218 The opposite of "to_json": expects a json string and tries to parse it, 219 returning the resulting reference. 220 221 This function call is functionally identical to: 222 223 $perl_scalar = JSON->decode($json_text) 224 225 Takes a hash reference as the second. 226 227 $perl_scalar = from_json($json_text, $flag_hashref) 228 229 So, 230 231 $perl_scalar = from_json($json_text, {utf8 => 1}) 232 233 equivalent to: 234 235 $perl_scalar = JSON->new->utf8(1)->decode($json_text) 236 237 If you want to write a modern perl code which communicates to outer 238 world, you should use "decode_json" (supposed that JSON data are encoded 239 in UTF-8). 240 241 JSON::is_bool 242 $is_boolean = JSON::is_bool($scalar) 243 244 Returns true if the passed scalar represents either JSON::true or 245 JSON::false, two constants that act like 1 and 0 respectively and are 246 also used to represent JSON "true" and "false" in Perl strings. 247 248 JSON::true 249 Returns JSON true value which is blessed object. It "isa" JSON::Boolean 250 object. 251 252 JSON::false 253 Returns JSON false value which is blessed object. It "isa" JSON::Boolean 254 object. 255 256 JSON::null 257 Returns "undef". 258 259 See MAPPING, below, for more information on how JSON values are mapped 260 to Perl. 261 262HOW DO I DECODE A DATA FROM OUTER AND ENCODE TO OUTER 263 This section supposes that your perl vresion is 5.8 or later. 264 265 If you know a JSON text from an outer world - a network, a file content, 266 and so on, is encoded in UTF-8, you should use "decode_json" or "JSON" 267 module object with "utf8" enable. And the decoded result will contain 268 UNICODE characters. 269 270 # from network 271 my $json = JSON->new->utf8; 272 my $json_text = CGI->new->param( 'json_data' ); 273 my $perl_scalar = $json->decode( $json_text ); 274 275 # from file content 276 local $/; 277 open( my $fh, '<', 'json.data' ); 278 $json_text = <$fh>; 279 $perl_scalar = decode_json( $json_text ); 280 281 If an outer data is not encoded in UTF-8, firstly you should "decode" 282 it. 283 284 use Encode; 285 local $/; 286 open( my $fh, '<', 'json.data' ); 287 my $encoding = 'cp932'; 288 my $unicode_json_text = decode( $encoding, <$fh> ); # UNICODE 289 290 # or you can write the below code. 291 # 292 # open( my $fh, "<:encoding($encoding)", 'json.data' ); 293 # $unicode_json_text = <$fh>; 294 295 In this case, $unicode_json_text is of course UNICODE string. So you 296 cannot use "decode_json" nor "JSON" module object with "utf8" enable. 297 Instead of them, you use "JSON" module object with "utf8" disable or 298 "from_json". 299 300 $perl_scalar = $json->utf8(0)->decode( $unicode_json_text ); 301 # or 302 $perl_scalar = from_json( $unicode_json_text ); 303 304 Or "encode 'utf8'" and "decode_json": 305 306 $perl_scalar = decode_json( encode( 'utf8', $unicode_json_text ) ); 307 # this way is not efficient. 308 309 And now, you want to convert your $perl_scalar into JSON data and send 310 it to an outer world - a network or a file content, and so on. 311 312 Your data usually contains UNICODE strings and you want the converted 313 data to be encoded in UTF-8, you should use "encode_json" or "JSON" 314 module object with "utf8" enable. 315 316 print encode_json( $perl_scalar ); # to a network? file? or display? 317 # or 318 print $json->utf8->encode( $perl_scalar ); 319 320 If $perl_scalar does not contain UNICODE but $encoding-encoded strings 321 for some reason, then its characters are regarded as latin1 for perl 322 (because it does not concern with your $encoding). You cannot use 323 "encode_json" nor "JSON" module object with "utf8" enable. Instead of 324 them, you use "JSON" module object with "utf8" disable or "to_json". 325 Note that the resulted text is a UNICODE string but no problem to print 326 it. 327 328 # $perl_scalar contains $encoding encoded string values 329 $unicode_json_text = $json->utf8(0)->encode( $perl_scalar ); 330 # or 331 $unicode_json_text = to_json( $perl_scalar ); 332 # $unicode_json_text consists of characters less than 0x100 333 print $unicode_json_text; 334 335 Or "decode $encoding" all string values and "encode_json": 336 337 $perl_scalar->{ foo } = decode( $encoding, $perl_scalar->{ foo } ); 338 # ... do it to each string values, then encode_json 339 $json_text = encode_json( $perl_scalar ); 340 341 This method is a proper way but probably not efficient. 342 343 See to Encode, perluniintro. 344 345COMMON OBJECT-ORIENTED INTERFACE 346 new 347 $json = JSON->new 348 349 Returns a new "JSON" object inherited from either JSON::XS or JSON::PP 350 that can be used to de/encode JSON strings. 351 352 All boolean flags described below are by default *disabled*. 353 354 The mutators for flags all return the JSON object again and thus calls 355 can be chained: 356 357 my $json = JSON->new->utf8->space_after->encode({a => [1,2]}) 358 => {"a": [1, 2]} 359 360 ascii 361 $json = $json->ascii([$enable]) 362 363 $enabled = $json->get_ascii 364 365 If $enable is true (or missing), then the encode method will not 366 generate characters outside the code range 0..127. Any Unicode 367 characters outside that range will be escaped using either a single 368 \uXXXX or a double \uHHHH\uLLLLL escape sequence, as per RFC4627. 369 370 If $enable is false, then the encode method will not escape Unicode 371 characters unless required by the JSON syntax or other flags. This 372 results in a faster and more compact format. 373 374 This feature depends on the used Perl version and environment. 375 376 See to "UNICODE HANDLING ON PERLS" in JSON::PP if the backend is PP. 377 378 JSON->new->ascii(1)->encode([chr 0x10401]) 379 => ["\ud801\udc01"] 380 381 latin1 382 $json = $json->latin1([$enable]) 383 384 $enabled = $json->get_latin1 385 386 If $enable is true (or missing), then the encode method will encode the 387 resulting JSON text as latin1 (or iso-8859-1), escaping any characters 388 outside the code range 0..255. 389 390 If $enable is false, then the encode method will not escape Unicode 391 characters unless required by the JSON syntax or other flags. 392 393 JSON->new->latin1->encode (["\x{89}\x{abc}"] 394 => ["\x{89}\\u0abc"] # (perl syntax, U+abc escaped, U+89 not) 395 396 utf8 397 $json = $json->utf8([$enable]) 398 399 $enabled = $json->get_utf8 400 401 If $enable is true (or missing), then the encode method will encode the 402 JSON result into UTF-8, as required by many protocols, while the decode 403 method expects to be handled an UTF-8-encoded string. Please note that 404 UTF-8-encoded strings do not contain any characters outside the range 405 0..255, they are thus useful for bytewise/binary I/O. 406 407 In future versions, enabling this option might enable autodetection of 408 the UTF-16 and UTF-32 encoding families, as described in RFC4627. 409 410 If $enable is false, then the encode method will return the JSON string 411 as a (non-encoded) Unicode string, while decode expects thus a Unicode 412 string. Any decoding or encoding (e.g. to UTF-8 or UTF-16) needs to be 413 done yourself, e.g. using the Encode module. 414 415 Example, output UTF-16BE-encoded JSON: 416 417 use Encode; 418 $jsontext = encode "UTF-16BE", JSON::XS->new->encode ($object); 419 420 Example, decode UTF-32LE-encoded JSON: 421 422 use Encode; 423 $object = JSON::XS->new->decode (decode "UTF-32LE", $jsontext); 424 425 See to "UNICODE HANDLING ON PERLS" in JSON::PP if the backend is PP. 426 427 pretty 428 $json = $json->pretty([$enable]) 429 430 This enables (or disables) all of the "indent", "space_before" and 431 "space_after" (and in the future possibly more) flags in one call to 432 generate the most readable (or most compact) form possible. 433 434 Equivalent to: 435 436 $json->indent->space_before->space_after 437 438 The indent space length is three and JSON::XS cannot change the indent 439 space length. 440 441 indent 442 $json = $json->indent([$enable]) 443 444 $enabled = $json->get_indent 445 446 If $enable is true (or missing), then the "encode" method will use a 447 multiline format as output, putting every array member or object/hash 448 key-value pair into its own line, identing them properly. 449 450 If $enable is false, no newlines or indenting will be produced, and the 451 resulting JSON text is guarenteed not to contain any "newlines". 452 453 This setting has no effect when decoding JSON texts. 454 455 The indent space length is three. With JSON::PP, you can also access 456 "indent_length" to change indent space length. 457 458 space_before 459 $json = $json->space_before([$enable]) 460 461 $enabled = $json->get_space_before 462 463 If $enable is true (or missing), then the "encode" method will add an 464 extra optional space before the ":" separating keys from values in JSON 465 objects. 466 467 If $enable is false, then the "encode" method will not add any extra 468 space at those places. 469 470 This setting has no effect when decoding JSON texts. 471 472 Example, space_before enabled, space_after and indent disabled: 473 474 {"key" :"value"} 475 476 space_after 477 $json = $json->space_after([$enable]) 478 479 $enabled = $json->get_space_after 480 481 If $enable is true (or missing), then the "encode" method will add an 482 extra optional space after the ":" separating keys from values in JSON 483 objects and extra whitespace after the "," separating key-value pairs 484 and array members. 485 486 If $enable is false, then the "encode" method will not add any extra 487 space at those places. 488 489 This setting has no effect when decoding JSON texts. 490 491 Example, space_before and indent disabled, space_after enabled: 492 493 {"key": "value"} 494 495 relaxed 496 $json = $json->relaxed([$enable]) 497 498 $enabled = $json->get_relaxed 499 500 If $enable is true (or missing), then "decode" will accept some 501 extensions to normal JSON syntax (see below). "encode" will not be 502 affected in anyway. *Be aware that this option makes you accept invalid 503 JSON texts as if they were valid!*. I suggest only to use this option to 504 parse application-specific files written by humans (configuration files, 505 resource files etc.) 506 507 If $enable is false (the default), then "decode" will only accept valid 508 JSON texts. 509 510 Currently accepted extensions are: 511 512 * list items can have an end-comma 513 514 JSON *separates* array elements and key-value pairs with commas. 515 This can be annoying if you write JSON texts manually and want to be 516 able to quickly append elements, so this extension accepts comma at 517 the end of such items not just between them: 518 519 [ 520 1, 521 2, <- this comma not normally allowed 522 ] 523 { 524 "k1": "v1", 525 "k2": "v2", <- this comma not normally allowed 526 } 527 528 * shell-style '#'-comments 529 530 Whenever JSON allows whitespace, shell-style comments are 531 additionally allowed. They are terminated by the first 532 carriage-return or line-feed character, after which more white-space 533 and comments are allowed. 534 535 [ 536 1, # this comment not allowed in JSON 537 # neither this one... 538 ] 539 540 canonical 541 $json = $json->canonical([$enable]) 542 543 $enabled = $json->get_canonical 544 545 If $enable is true (or missing), then the "encode" method will output 546 JSON objects by sorting their keys. This is adding a comparatively high 547 overhead. 548 549 If $enable is false, then the "encode" method will output key-value 550 pairs in the order Perl stores them (which will likely change between 551 runs of the same script). 552 553 This option is useful if you want the same data structure to be encoded 554 as the same JSON text (given the same overall settings). If it is 555 disabled, the same hash might be encoded differently even if contains 556 the same data, as key-value pairs have no inherent ordering in Perl. 557 558 This setting has no effect when decoding JSON texts. 559 560 allow_nonref 561 $json = $json->allow_nonref([$enable]) 562 563 $enabled = $json->get_allow_nonref 564 565 If $enable is true (or missing), then the "encode" method can convert a 566 non-reference into its corresponding string, number or null JSON value, 567 which is an extension to RFC4627. Likewise, "decode" will accept those 568 JSON values instead of croaking. 569 570 If $enable is false, then the "encode" method will croak if it isn't 571 passed an arrayref or hashref, as JSON texts must either be an object or 572 array. Likewise, "decode" will croak if given something that is not a 573 JSON object or array. 574 575 JSON->new->allow_nonref->encode ("Hello, World!") 576 => "Hello, World!" 577 578 allow_unknown 579 $json = $json->allow_unknown ([$enable]) 580 581 $enabled = $json->get_allow_unknown 582 583 If $enable is true (or missing), then "encode" will *not* throw an 584 exception when it encounters values it cannot represent in JSON (for 585 example, filehandles) but instead will encode a JSON "null" value. Note 586 that blessed objects are not included here and are handled separately by 587 c<allow_nonref>. 588 589 If $enable is false (the default), then "encode" will throw an exception 590 when it encounters anything it cannot encode as JSON. 591 592 This option does not affect "decode" in any way, and it is recommended 593 to leave it off unless you know your communications partner. 594 595 allow_blessed 596 $json = $json->allow_blessed([$enable]) 597 598 $enabled = $json->get_allow_blessed 599 600 If $enable is true (or missing), then the "encode" method will not barf 601 when it encounters a blessed reference. Instead, the value of the 602 convert_blessed option will decide whether "null" ("convert_blessed" 603 disabled or no "TO_JSON" method found) or a representation of the object 604 ("convert_blessed" enabled and "TO_JSON" method found) is being encoded. 605 Has no effect on "decode". 606 607 If $enable is false (the default), then "encode" will throw an exception 608 when it encounters a blessed object. 609 610 convert_blessed 611 $json = $json->convert_blessed([$enable]) 612 613 $enabled = $json->get_convert_blessed 614 615 If $enable is true (or missing), then "encode", upon encountering a 616 blessed object, will check for the availability of the "TO_JSON" method 617 on the object's class. If found, it will be called in scalar context and 618 the resulting scalar will be encoded instead of the object. If no 619 "TO_JSON" method is found, the value of "allow_blessed" will decide what 620 to do. 621 622 The "TO_JSON" method may safely call die if it wants. If "TO_JSON" 623 returns other blessed objects, those will be handled in the same way. 624 "TO_JSON" must take care of not causing an endless recursion cycle (== 625 crash) in this case. The name of "TO_JSON" was chosen because other 626 methods called by the Perl core (== not by the user of the object) are 627 usually in upper case letters and to avoid collisions with the "to_json" 628 function or method. 629 630 This setting does not yet influence "decode" in any way. 631 632 If $enable is false, then the "allow_blessed" setting will decide what 633 to do when a blessed object is found. 634 635 convert_blessed_universally mode 636 If use "JSON" with "-convert_blessed_universally", the 637 "UNIVERSAL::TO_JSON" subroutine is defined as the below code: 638 639 *UNIVERSAL::TO_JSON = sub { 640 my $b_obj = B::svref_2object( $_[0] ); 641 return $b_obj->isa('B::HV') ? { %{ $_[0] } } 642 : $b_obj->isa('B::AV') ? [ @{ $_[0] } ] 643 : undef 644 ; 645 } 646 647 This will cause that "encode" method converts simple blessed objects 648 into JSON objects as non-blessed object. 649 650 JSON -convert_blessed_universally; 651 $json->allow_blessed->convert_blessed->encode( $blessed_object ) 652 653 This feature is experimental and may be removed in the future. 654 655 filter_json_object 656 $json = $json->filter_json_object([$coderef]) 657 658 When $coderef is specified, it will be called from "decode" each time it 659 decodes a JSON object. The only argument passed to the coderef is a 660 reference to the newly-created hash. If the code references returns a 661 single scalar (which need not be a reference), this value (i.e. a copy 662 of that scalar to avoid aliasing) is inserted into the deserialised data 663 structure. If it returns an empty list (NOTE: *not* "undef", which is a 664 valid scalar), the original deserialised hash will be inserted. This 665 setting can slow down decoding considerably. 666 667 When $coderef is omitted or undefined, any existing callback will be 668 removed and "decode" will not change the deserialised hash in any way. 669 670 Example, convert all JSON objects into the integer 5: 671 672 my $js = JSON->new->filter_json_object (sub { 5 }); 673 # returns [5] 674 $js->decode ('[{}]'); # the given subroutine takes a hash reference. 675 # throw an exception because allow_nonref is not enabled 676 # so a lone 5 is not allowed. 677 $js->decode ('{"a":1, "b":2}'); 678 679 filter_json_single_key_object 680 $json = $json->filter_json_single_key_object($key [=> $coderef]) 681 682 Works remotely similar to "filter_json_object", but is only called for 683 JSON objects having a single key named $key. 684 685 This $coderef is called before the one specified via 686 "filter_json_object", if any. It gets passed the single value in the 687 JSON object. If it returns a single value, it will be inserted into the 688 data structure. If it returns nothing (not even "undef" but the empty 689 list), the callback from "filter_json_object" will be called next, as if 690 no single-key callback were specified. 691 692 If $coderef is omitted or undefined, the corresponding callback will be 693 disabled. There can only ever be one callback for a given key. 694 695 As this callback gets called less often then the "filter_json_object" 696 one, decoding speed will not usually suffer as much. Therefore, 697 single-key objects make excellent targets to serialise Perl objects 698 into, especially as single-key JSON objects are as close to the 699 type-tagged value concept as JSON gets (it's basically an ID/VALUE 700 tuple). Of course, JSON does not support this in any way, so you need to 701 make sure your data never looks like a serialised Perl hash. 702 703 Typical names for the single object key are "__class_whatever__", or 704 "$__dollars_are_rarely_used__$" or "}ugly_brace_placement", or even 705 things like "__class_md5sum(classname)__", to reduce the risk of 706 clashing with real hashes. 707 708 Example, decode JSON objects of the form "{ "__widget__" => <id> }" into 709 the corresponding $WIDGET{<id>} object: 710 711 # return whatever is in $WIDGET{5}: 712 JSON 713 ->new 714 ->filter_json_single_key_object (__widget__ => sub { 715 $WIDGET{ $_[0] } 716 }) 717 ->decode ('{"__widget__": 5') 718 719 # this can be used with a TO_JSON method in some "widget" class 720 # for serialisation to json: 721 sub WidgetBase::TO_JSON { 722 my ($self) = @_; 723 724 unless ($self->{id}) { 725 $self->{id} = ..get..some..id..; 726 $WIDGET{$self->{id}} = $self; 727 } 728 729 { __widget__ => $self->{id} } 730 } 731 732 shrink 733 $json = $json->shrink([$enable]) 734 735 $enabled = $json->get_shrink 736 737 With JSON::XS, this flag resizes strings generated by either "encode" or 738 "decode" to their minimum size possible. This can save memory when your 739 JSON texts are either very very long or you have many short strings. It 740 will also try to downgrade any strings to octet-form if possible: perl 741 stores strings internally either in an encoding called UTF-X or in 742 octet-form. The latter cannot store everything but uses less space in 743 general (and some buggy Perl or C code might even rely on that internal 744 representation being used). 745 746 With JSON::PP, it is noop about resizing strings but tries 747 "utf8::downgrade" to the returned string by "encode". See to utf8. 748 749 See to "OBJECT-ORIENTED INTERFACE" in JSON::XS and "METHODS" in 750 JSON::PP. 751 752 max_depth 753 $json = $json->max_depth([$maximum_nesting_depth]) 754 755 $max_depth = $json->get_max_depth 756 757 Sets the maximum nesting level (default 512) accepted while encoding or 758 decoding. If a higher nesting level is detected in JSON text or a Perl 759 data structure, then the encoder and decoder will stop and croak at that 760 point. 761 762 Nesting level is defined by number of hash- or arrayrefs that the 763 encoder needs to traverse to reach a given point or the number of "{" or 764 "[" characters without their matching closing parenthesis crossed to 765 reach a given character in a string. 766 767 If no argument is given, the highest possible setting will be used, 768 which is rarely useful. 769 770 Note that nesting is implemented by recursion in C. The default value 771 has been chosen to be as large as typical operating systems allow 772 without crashing. (JSON::XS) 773 774 With JSON::PP as the backend, when a large value (100 or more) was set 775 and it de/encodes a deep nested object/text, it may raise a warning 776 'Deep recursion on subroutin' at the perl runtime phase. 777 778 See "SECURITY CONSIDERATIONS" in JSON::XS for more info on why this is 779 useful. 780 781 max_size 782 $json = $json->max_size([$maximum_string_size]) 783 784 $max_size = $json->get_max_size 785 786 Set the maximum length a JSON text may have (in bytes) where decoding is 787 being attempted. The default is 0, meaning no limit. When "decode" is 788 called on a string that is longer then this many bytes, it will not 789 attempt to decode the string but throw an exception. This setting has no 790 effect on "encode" (yet). 791 792 If no argument is given, the limit check will be deactivated (same as 793 when 0 is specified). 794 795 See "SECURITY CONSIDERATIONS" in JSON::XS, below, for more info on why 796 this is useful. 797 798 encode 799 $json_text = $json->encode($perl_scalar) 800 801 Converts the given Perl data structure (a simple scalar or a reference 802 to a hash or array) to its JSON representation. Simple scalars will be 803 converted into JSON string or number sequences, while references to 804 arrays become JSON arrays and references to hashes become JSON objects. 805 Undefined Perl values (e.g. "undef") become JSON "null" values. 806 References to the integers 0 and 1 are converted into "true" and 807 "false". 808 809 decode 810 $perl_scalar = $json->decode($json_text) 811 812 The opposite of "encode": expects a JSON text and tries to parse it, 813 returning the resulting simple scalar or reference. Croaks on error. 814 815 JSON numbers and strings become simple Perl scalars. JSON arrays become 816 Perl arrayrefs and JSON objects become Perl hashrefs. "true" becomes 1 817 ("JSON::true"), "false" becomes 0 ("JSON::false") and "null" becomes 818 "undef". 819 820 decode_prefix 821 ($perl_scalar, $characters) = $json->decode_prefix($json_text) 822 823 This works like the "decode" method, but instead of raising an exception 824 when there is trailing garbage after the first JSON object, it will 825 silently stop parsing there and return the number of characters consumed 826 so far. 827 828 JSON->new->decode_prefix ("[1] the tail") 829 => ([], 3) 830 831 See to "OBJECT-ORIENTED INTERFACE" in JSON::XS 832 833 property 834 $boolean = $json->property($property_name) 835 836 Returns a boolean value about above some properties. 837 838 The available properties are "ascii", "latin1", "utf8", 839 "indent","space_before", "space_after", "relaxed", "canonical", 840 "allow_nonref", "allow_unknown", "allow_blessed", "convert_blessed", 841 "shrink", "max_depth" and "max_size". 842 843 $boolean = $json->property('utf8'); 844 => 0 845 $json->utf8; 846 $boolean = $json->property('utf8'); 847 => 1 848 849 Sets the property with a given boolean value. 850 851 $json = $json->property($property_name => $boolean); 852 853 With no argumnt, it returns all the above properties as a hash 854 reference. 855 856 $flag_hashref = $json->property(); 857 858INCREMENTAL PARSING 859 Most of this section are copied and modified from "INCREMENTAL PARSING" 860 in JSON::XS. 861 862 In some cases, there is the need for incremental parsing of JSON texts. 863 This module does allow you to parse a JSON stream incrementally. It does 864 so by accumulating text until it has a full JSON object, which it then 865 can decode. This process is similar to using "decode_prefix" to see if a 866 full JSON object is available, but is much more efficient (and can be 867 implemented with a minimum of method calls). 868 869 The backend module will only attempt to parse the JSON text once it is 870 sure it has enough text to get a decisive result, using a very simple 871 but truly incremental parser. This means that it sometimes won't stop as 872 early as the full parser, for example, it doesn't detect parenthese 873 mismatches. The only thing it guarantees is that it starts decoding as 874 soon as a syntactically valid JSON text has been seen. This means you 875 need to set resource limits (e.g. "max_size") to ensure the parser will 876 stop parsing in the presence if syntax errors. 877 878 The following methods implement this incremental parser. 879 880 incr_parse 881 $json->incr_parse( [$string] ) # void context 882 883 $obj_or_undef = $json->incr_parse( [$string] ) # scalar context 884 885 @obj_or_empty = $json->incr_parse( [$string] ) # list context 886 887 This is the central parsing function. It can both append new text and 888 extract objects from the stream accumulated so far (both of these 889 functions are optional). 890 891 If $string is given, then this string is appended to the already 892 existing JSON fragment stored in the $json object. 893 894 After that, if the function is called in void context, it will simply 895 return without doing anything further. This can be used to add more text 896 in as many chunks as you want. 897 898 If the method is called in scalar context, then it will try to extract 899 exactly *one* JSON object. If that is successful, it will return this 900 object, otherwise it will return "undef". If there is a parse error, 901 this method will croak just as "decode" would do (one can then use 902 "incr_skip" to skip the errornous part). This is the most common way of 903 using the method. 904 905 And finally, in list context, it will try to extract as many objects 906 from the stream as it can find and return them, or the empty list 907 otherwise. For this to work, there must be no separators between the 908 JSON objects or arrays, instead they must be concatenated back-to-back. 909 If an error occurs, an exception will be raised as in the scalar context 910 case. Note that in this case, any previously-parsed JSON texts will be 911 lost. 912 913 Example: Parse some JSON arrays/objects in a given string and return 914 them. 915 916 my @objs = JSON->new->incr_parse ("[5][7][1,2]"); 917 918 incr_text 919 $lvalue_string = $json->incr_text 920 921 This method returns the currently stored JSON fragment as an lvalue, 922 that is, you can manipulate it. This *only* works when a preceding call 923 to "incr_parse" in *scalar context* successfully returned an object. 924 Under all other circumstances you must not call this function (I mean 925 it. although in simple tests it might actually work, it *will* fail 926 under real world conditions). As a special exception, you can also call 927 this method before having parsed anything. 928 929 This function is useful in two cases: a) finding the trailing text after 930 a JSON object or b) parsing multiple JSON objects separated by non-JSON 931 text (such as commas). 932 933 $json->incr_text =~ s/\s*,\s*//; 934 935 In Perl 5.005, "lvalue" attribute is not available. You must write codes 936 like the below: 937 938 $string = $json->incr_text; 939 $string =~ s/\s*,\s*//; 940 $json->incr_text( $string ); 941 942 incr_skip 943 $json->incr_skip 944 945 This will reset the state of the incremental parser and will remove the 946 parsed text from the input buffer. This is useful after "incr_parse" 947 died, in which case the input buffer and incremental parser state is 948 left unchanged, to skip the text parsed so far and to reset the parse 949 state. 950 951 incr_reset 952 $json->incr_reset 953 954 This completely resets the incremental parser, that is, after this call, 955 it will be as if the parser had never parsed anything. 956 957 This is useful if you want ot repeatedly parse JSON objects and want to 958 ignore any trailing data, which means you have to reset the parser after 959 each successful decode. 960 961 See to "INCREMENTAL PARSING" in JSON::XS for examples. 962 963JSON::PP SUPPORT METHODS 964 The below methods are JSON::PP own methods, so when "JSON" works with 965 JSON::PP (i.e. the created object is a JSON::PP object), available. See 966 to "JSON::PP OWN METHODS" in JSON::PP in detail. 967 968 If you use "JSON" with additonal "-support_by_pp", some methods are 969 available even with JSON::XS. See to "USE PP FEATURES EVEN THOUGH XS 970 BACKEND". 971 972 BEING { $ENV{PERL_JSON_BACKEND} = 'JSON::XS' } 973 974 use JSON -support_by_pp; 975 976 my $json = new JSON; 977 $json->allow_nonref->escape_slash->encode("/"); 978 979 # functional interfaces too. 980 print to_json(["/"], {escape_slash => 1}); 981 print from_json('["foo"]', {utf8 => 1}); 982 983 If you do not want to all functions but "-support_by_pp", use 984 "-no_export". 985 986 use JSON -support_by_pp, -no_export; 987 # functional interfaces are not exported. 988 989 allow_singlequote 990 $json = $json->allow_singlequote([$enable]) 991 992 If $enable is true (or missing), then "decode" will accept any JSON 993 strings quoted by single quotations that are invalid JSON format. 994 995 $json->allow_singlequote->decode({"foo":'bar'}); 996 $json->allow_singlequote->decode({'foo':"bar"}); 997 $json->allow_singlequote->decode({'foo':'bar'}); 998 999 As same as the "relaxed" option, this option may be used to parse 1000 application-specific files written by humans. 1001 1002 allow_barekey 1003 $json = $json->allow_barekey([$enable]) 1004 1005 If $enable is true (or missing), then "decode" will accept bare keys of 1006 JSON object that are invalid JSON format. 1007 1008 As same as the "relaxed" option, this option may be used to parse 1009 application-specific files written by humans. 1010 1011 $json->allow_barekey->decode('{foo:"bar"}'); 1012 1013 allow_bignum 1014 $json = $json->allow_bignum([$enable]) 1015 1016 If $enable is true (or missing), then "decode" will convert the big 1017 integer Perl cannot handle as integer into a Math::BigInt object and 1018 convert a floating number (any) into a Math::BigFloat. 1019 1020 On the contary, "encode" converts "Math::BigInt" objects and 1021 "Math::BigFloat" objects into JSON numbers with "allow_blessed" enable. 1022 1023 $json->allow_nonref->allow_blessed->allow_bignum; 1024 $bigfloat = $json->decode('2.000000000000000000000000001'); 1025 print $json->encode($bigfloat); 1026 # => 2.000000000000000000000000001 1027 1028 See to MAPPING aboout the conversion of JSON number. 1029 1030 loose 1031 $json = $json->loose([$enable]) 1032 1033 The unescaped [\x00-\x1f\x22\x2f\x5c] strings are invalid in JSON 1034 strings and the module doesn't allow to "decode" to these (except for 1035 \x2f). If $enable is true (or missing), then "decode" will accept these 1036 unescaped strings. 1037 1038 $json->loose->decode(qq|["abc 1039 def"]|); 1040 1041 See to "JSON::PP OWN METHODS" in JSON::PP. 1042 1043 escape_slash 1044 $json = $json->escape_slash([$enable]) 1045 1046 According to JSON Grammar, *slash* (U+002F) is escaped. But by default 1047 JSON backend modules encode strings without escaping slash. 1048 1049 If $enable is true (or missing), then "encode" will escape slashes. 1050 1051 indent_length 1052 $json = $json->indent_length($length) 1053 1054 With JSON::XS, The indent space length is 3 and cannot be changed. With 1055 JSON::PP, it sets the indent space length with the given $length. The 1056 default is 3. The acceptable range is 0 to 15. 1057 1058 sort_by 1059 $json = $json->sort_by($function_name) 1060 $json = $json->sort_by($subroutine_ref) 1061 1062 If $function_name or $subroutine_ref are set, its sort routine are used. 1063 1064 $js = $pc->sort_by(sub { $JSON::PP::a cmp $JSON::PP::b })->encode($obj); 1065 # is($js, q|{"a":1,"b":2,"c":3,"d":4,"e":5,"f":6,"g":7,"h":8,"i":9}|); 1066 1067 $js = $pc->sort_by('own_sort')->encode($obj); 1068 # is($js, q|{"a":1,"b":2,"c":3,"d":4,"e":5,"f":6,"g":7,"h":8,"i":9}|); 1069 1070 sub JSON::PP::own_sort { $JSON::PP::a cmp $JSON::PP::b } 1071 1072 As the sorting routine runs in the JSON::PP scope, the given subroutine 1073 name and the special variables $a, $b will begin with 'JSON::PP::'. 1074 1075 If $integer is set, then the effect is same as "canonical" on. 1076 1077 See to "JSON::PP OWN METHODS" in JSON::PP. 1078 1079MAPPING 1080 This section is copied from JSON::XS and modified to "JSON". JSON::XS 1081 and JSON::PP mapping mechanisms are almost equivalent. 1082 1083 See to "MAPPING" in JSON::XS. 1084 1085 JSON -> PERL 1086 object 1087 A JSON object becomes a reference to a hash in Perl. No ordering of 1088 object keys is preserved (JSON does not preserver object key 1089 ordering itself). 1090 1091 array 1092 A JSON array becomes a reference to an array in Perl. 1093 1094 string 1095 A JSON string becomes a string scalar in Perl - Unicode codepoints 1096 in JSON are represented by the same codepoints in the Perl string, 1097 so no manual decoding is necessary. 1098 1099 number 1100 A JSON number becomes either an integer, numeric (floating point) or 1101 string scalar in perl, depending on its range and any fractional 1102 parts. On the Perl level, there is no difference between those as 1103 Perl handles all the conversion details, but an integer may take 1104 slightly less memory and might represent more values exactly than 1105 floating point numbers. 1106 1107 If the number consists of digits only, "JSON" will try to represent 1108 it as an integer value. If that fails, it will try to represent it 1109 as a numeric (floating point) value if that is possible without loss 1110 of precision. Otherwise it will preserve the number as a string 1111 value (in which case you lose roundtripping ability, as the JSON 1112 number will be re-encoded toa JSON string). 1113 1114 Numbers containing a fractional or exponential part will always be 1115 represented as numeric (floating point) values, possibly at a loss 1116 of precision (in which case you might lose perfect roundtripping 1117 ability, but the JSON number will still be re-encoded as a JSON 1118 number). 1119 1120 Note that precision is not accuracy - binary floating point values 1121 cannot represent most decimal fractions exactly, and when converting 1122 from and to floating point, "JSON" only guarantees precision up to 1123 but not including the leats significant bit. 1124 1125 If the backend is JSON::PP and "allow_bignum" is enable, the big 1126 integers and the numeric can be optionally converted into 1127 Math::BigInt and Math::BigFloat objects. 1128 1129 true, false 1130 These JSON atoms become "JSON::true" and "JSON::false", 1131 respectively. They are overloaded to act almost exactly like the 1132 numbers 1 and 0. You can check wether a scalar is a JSON boolean by 1133 using the "JSON::is_bool" function. 1134 1135 If "JSON::true" and "JSON::false" are used as strings or compared as 1136 strings, they represent as "true" and "false" respectively. 1137 1138 print JSON::true . "\n"; 1139 => true 1140 print JSON::true + 1; 1141 => 1 1142 1143 ok(JSON::true eq 'true'); 1144 ok(JSON::true eq '1'); 1145 ok(JSON::true == 1); 1146 1147 "JSON" will install these missing overloading features to the 1148 backend modules. 1149 1150 null 1151 A JSON null atom becomes "undef" in Perl. 1152 1153 "JSON::null" returns "unddef". 1154 1155 PERL -> JSON 1156 The mapping from Perl to JSON is slightly more difficult, as Perl is a 1157 truly typeless language, so we can only guess which JSON type is meant 1158 by a Perl value. 1159 1160 hash references 1161 Perl hash references become JSON objects. As there is no inherent 1162 ordering in hash keys (or JSON objects), they will usually be 1163 encoded in a pseudo-random order that can change between runs of the 1164 same program but stays generally the same within a single run of a 1165 program. "JSON" optionally sort the hash keys (determined by the 1166 *canonical* flag), so the same datastructure will serialise to the 1167 same JSON text (given same settings and version of JSON::XS), but 1168 this incurs a runtime overhead and is only rarely useful, e.g. when 1169 you want to compare some JSON text against another for equality. 1170 1171 In future, the ordered object feature will be added to JSON::PP 1172 using "tie" mechanism. 1173 1174 array references 1175 Perl array references become JSON arrays. 1176 1177 other references 1178 Other unblessed references are generally not allowed and will cause 1179 an exception to be thrown, except for references to the integers 0 1180 and 1, which get turned into "false" and "true" atoms in JSON. You 1181 can also use "JSON::false" and "JSON::true" to improve readability. 1182 1183 to_json [\0,JSON::true] # yields [false,true] 1184 1185 JSON::true, JSON::false, JSON::null 1186 These special values become JSON true and JSON false values, 1187 respectively. You can also use "\1" and "\0" directly if you want. 1188 1189 JSON::null returns "undef". 1190 1191 blessed objects 1192 Blessed objects are not directly representable in JSON. See the 1193 "allow_blessed" and "convert_blessed" methods on various options on 1194 how to deal with this: basically, you can choose between throwing an 1195 exception, encoding the reference as if it weren't blessed, or 1196 provide your own serialiser method. 1197 1198 With "convert_blessed_universally" mode, "encode" converts blessed 1199 hash references or blessed array references (contains other blessed 1200 references) into JSON members and arrays. 1201 1202 use JSON -convert_blessed_universally; 1203 JSON->new->allow_blessed->convert_blessed->encode( $blessed_object ); 1204 1205 See to convert_blessed. 1206 1207 simple scalars 1208 Simple Perl scalars (any scalar that is not a reference) are the 1209 most difficult objects to encode: JSON::XS and JSON::PP will encode 1210 undefined scalars as JSON "null" values, scalars that have last been 1211 used in a string context before encoding as JSON strings, and 1212 anything else as number value: 1213 1214 # dump as number 1215 encode_json [2] # yields [2] 1216 encode_json [-3.0e17] # yields [-3e+17] 1217 my $value = 5; encode_json [$value] # yields [5] 1218 1219 # used as string, so dump as string 1220 print $value; 1221 encode_json [$value] # yields ["5"] 1222 1223 # undef becomes null 1224 encode_json [undef] # yields [null] 1225 1226 You can force the type to be a string by stringifying it: 1227 1228 my $x = 3.1; # some variable containing a number 1229 "$x"; # stringified 1230 $x .= ""; # another, more awkward way to stringify 1231 print $x; # perl does it for you, too, quite often 1232 1233 You can force the type to be a number by numifying it: 1234 1235 my $x = "3"; # some variable containing a string 1236 $x += 0; # numify it, ensuring it will be dumped as a number 1237 $x *= 1; # same thing, the choise is yours. 1238 1239 You can not currently force the type in other, less obscure, ways. 1240 1241 Note that numerical precision has the same meaning as under Perl (so 1242 binary to decimal conversion follows the same rules as in Perl, 1243 which can differ to other languages). Also, your perl interpreter 1244 might expose extensions to the floating point numbers of your 1245 platform, such as infinities or NaN's - these cannot be represented 1246 in JSON, and it is an error to pass those in. 1247 1248 Big Number 1249 If the backend is JSON::PP and "allow_bignum" is enable, "encode" 1250 converts "Math::BigInt" objects and "Math::BigFloat" objects into 1251 JSON numbers. 1252 1253JSON and ECMAscript 1254 See to "JSON and ECMAscript" in JSON::XS. 1255 1256JSON and YAML 1257 JSON is not a subset of YAML. See to "JSON and YAML" in JSON::XS. 1258 1259BACKEND MODULE DECISION 1260 When you use "JSON", "JSON" tries to "use" JSON::XS. If this call 1261 failed, it will "uses" JSON::PP. The required JSON::XS version is *2.2* 1262 or later. 1263 1264 The "JSON" constructor method returns an object inherited from the 1265 backend module, and JSON::XS object is a blessed scaler reference while 1266 JSON::PP is a blessed hash reference. 1267 1268 So, your program should not depend on the backend module, especially 1269 returned objects should not be modified. 1270 1271 my $json = JSON->new; # XS or PP? 1272 $json->{stash} = 'this is xs object'; # this code may raise an error! 1273 1274 To check the backend module, there are some methods - "backend", "is_pp" 1275 and "is_xs". 1276 1277 JSON->backend; # 'JSON::XS' or 'JSON::PP' 1278 1279 JSON->backend->is_pp: # 0 or 1 1280 1281 JSON->backend->is_xs: # 1 or 0 1282 1283 $json->is_xs; # 1 or 0 1284 1285 $json->is_pp; # 0 or 1 1286 1287 If you set an enviornment variable "PERL_JSON_BACKEND", The calling 1288 action will be changed. 1289 1290 PERL_JSON_BACKEND = 0 or PERL_JSON_BACKEND = 'JSON::PP' 1291 Always use JSON::PP 1292 1293 PERL_JSON_BACKEND == 1 or PERL_JSON_BACKEND = 'JSON::XS,JSON::PP' 1294 (The default) Use compiled JSON::XS if it is properly compiled & 1295 installed, otherwise use JSON::PP. 1296 1297 PERL_JSON_BACKEND == 2 or PERL_JSON_BACKEND = 'JSON::XS' 1298 Always use compiled JSON::XS, die if it isn't properly compiled & 1299 installed. 1300 1301 PERL_JSON_BACKEND = 'JSON::backportPP' 1302 Always use JSON::backportPP. JSON::backportPP is JSON::PP back port 1303 module. "JSON" includs JSON::backportPP instead of JSON::PP. 1304 1305 These ideas come from DBI::PurePerl mechanism. 1306 1307 example: 1308 1309 BEGIN { $ENV{PERL_JSON_BACKEND} = 'JSON::PP' } 1310 use JSON; # always uses JSON::PP 1311 1312 In future, it may be able to specify another module. 1313 1314USE PP FEATURES EVEN THOUGH XS BACKEND 1315 Many methods are available with either JSON::XS or JSON::PP and when the 1316 backend module is JSON::XS, if any JSON::PP specific (i.e. JSON::XS 1317 unspported) method is called, it will "warn" and be noop. 1318 1319 But If you "use" "JSON" passing the optional string "-support_by_pp", it 1320 makes a part of those unupported methods available. This feature is 1321 achieved by using JSON::PP in "de/encode". 1322 1323 BEGIN { $ENV{PERL_JSON_BACKEND} = 2 } # with JSON::XS 1324 use JSON -support_by_pp; 1325 my $json = new JSON; 1326 $json->allow_nonref->escape_slash->encode("/"); 1327 1328 At this time, the returned object is a "JSON::Backend::XS::Supportable" 1329 object (re-blessed XS object), and by checking JSON::XS unsupported 1330 flags in de/encoding, can support some unsupported methods - "loose", 1331 "allow_bignum", "allow_barekey", "allow_singlequote", "escape_slash" and 1332 "indent_length". 1333 1334 When any unsupported methods are not enable, "XS de/encode" will be used 1335 as is. The switch is achieved by changing the symbolic tables. 1336 1337 "-support_by_pp" is effective only when the backend module is JSON::XS 1338 and it makes the de/encoding speed down a bit. 1339 1340 See to "JSON::PP SUPPORT METHODS". 1341 1342INCOMPATIBLE CHANGES TO OLD VERSION 1343 There are big incompatibility between new version (2.00) and old (1.xx). 1344 If you use old "JSON" 1.xx in your code, please check it. 1345 1346 See to "Transition ways from 1.xx to 2.xx." 1347 1348 jsonToObj and objToJson are obsoleted. 1349 Non Perl-style name "jsonToObj" and "objToJson" are obsoleted (but 1350 not yet deleted from the source). If you use these functions in your 1351 code, please replace them with "from_json" and "to_json". 1352 1353 Global variables are no longer available. 1354 "JSON" class variables - $JSON::AUTOCONVERT, $JSON::BareKey, etc... 1355 - are not available any longer. Instead, various features can be 1356 used through object methods. 1357 1358 Package JSON::Converter and JSON::Parser are deleted. 1359 Now "JSON" bundles with JSON::PP which can handle JSON more properly 1360 than them. 1361 1362 Package JSON::NotString is deleted. 1363 There was "JSON::NotString" class which represents JSON value 1364 "true", "false", "null" and numbers. It was deleted and replaced by 1365 "JSON::Boolean". 1366 1367 "JSON::Boolean" represents "true" and "false". 1368 1369 "JSON::Boolean" does not represent "null". 1370 1371 "JSON::null" returns "undef". 1372 1373 "JSON" makes JSON::XS::Boolean and JSON::PP::Boolean is-a relation 1374 to JSON::Boolean. 1375 1376 function JSON::Number is obsoleted. 1377 "JSON::Number" is now needless because JSON::XS and JSON::PP have 1378 round-trip integrity. 1379 1380 JSONRPC modules are deleted. 1381 Perl implementation of JSON-RPC protocol - "JSONRPC ", 1382 "JSONRPC::Transport::HTTP" and "Apache::JSONRPC " are deleted in 1383 this distribution. Instead of them, there is JSON::RPC which 1384 supports JSON-RPC protocol version 1.1. 1385 1386 Transition ways from 1.xx to 2.xx. 1387 You should set "suport_by_pp" mode firstly, because it is always 1388 successful for the below codes even with JSON::XS. 1389 1390 use JSON -support_by_pp; 1391 1392 Exported jsonToObj (simple) 1393 from_json($json_text); 1394 1395 Exported objToJson (simple) 1396 to_json($perl_scalar); 1397 1398 Exported jsonToObj (advanced) 1399 $flags = {allow_barekey => 1, allow_singlequote => 1}; 1400 from_json($json_text, $flags); 1401 1402 equivalent to: 1403 1404 $JSON::BareKey = 1; 1405 $JSON::QuotApos = 1; 1406 jsonToObj($json_text); 1407 1408 Exported objToJson (advanced) 1409 $flags = {allow_blessed => 1, allow_barekey => 1}; 1410 to_json($perl_scalar, $flags); 1411 1412 equivalent to: 1413 1414 $JSON::BareKey = 1; 1415 objToJson($perl_scalar); 1416 1417 jsonToObj as object method 1418 $json->decode($json_text); 1419 1420 objToJson as object method 1421 $json->encode($perl_scalar); 1422 1423 new method with parameters 1424 The "new" method in 2.x takes any parameters no longer. You can set 1425 parameters instead; 1426 1427 $json = JSON->new->pretty; 1428 1429 $JSON::Pretty, $JSON::Indent, $JSON::Delimiter 1430 If "indent" is enable, that means $JSON::Pretty flag set. And 1431 $JSON::Delimiter was substituted by "space_before" and 1432 "space_after". In conclusion: 1433 1434 $json->indent->space_before->space_after; 1435 1436 Equivalent to: 1437 1438 $json->pretty; 1439 1440 To change indent length, use "indent_length". 1441 1442 (Only with JSON::PP, if "-support_by_pp" is not used.) 1443 1444 $json->pretty->indent_length(2)->encode($perl_scalar); 1445 1446 $JSON::BareKey 1447 (Only with JSON::PP, if "-support_by_pp" is not used.) 1448 1449 $json->allow_barekey->decode($json_text) 1450 1451 $JSON::ConvBlessed 1452 use "-convert_blessed_universally". See to convert_blessed. 1453 1454 $JSON::QuotApos 1455 (Only with JSON::PP, if "-support_by_pp" is not used.) 1456 1457 $json->allow_singlequote->decode($json_text) 1458 1459 $JSON::SingleQuote 1460 Disable. "JSON" does not make such a invalid JSON string any longer. 1461 1462 $JSON::KeySort 1463 $json->canonical->encode($perl_scalar) 1464 1465 This is the ascii sort. 1466 1467 If you want to use with your own sort routine, check the "sort_by" 1468 method. 1469 1470 (Only with JSON::PP, even if "-support_by_pp" is used currently.) 1471 1472 $json->sort_by($sort_routine_ref)->encode($perl_scalar) 1473 1474 $json->sort_by(sub { $JSON::PP::a <=> $JSON::PP::b })->encode($perl_scalar) 1475 1476 Can't access $a and $b but $JSON::PP::a and $JSON::PP::b. 1477 1478 $JSON::SkipInvalid 1479 $json->allow_unknown 1480 1481 $JSON::AUTOCONVERT 1482 Needless. "JSON" backend modules have the round-trip integrity. 1483 1484 $JSON::UTF8 1485 Needless because "JSON" (JSON::XS/JSON::PP) sets the UTF8 flag on 1486 properly. 1487 1488 # With UTF8-flagged strings 1489 1490 $json->allow_nonref; 1491 $str = chr(1000); # UTF8-flagged 1492 1493 $json_text = $json->utf8(0)->encode($str); 1494 utf8::is_utf8($json_text); 1495 # true 1496 $json_text = $json->utf8(1)->encode($str); 1497 utf8::is_utf8($json_text); 1498 # false 1499 1500 $str = '"' . chr(1000) . '"'; # UTF8-flagged 1501 1502 $perl_scalar = $json->utf8(0)->decode($str); 1503 utf8::is_utf8($perl_scalar); 1504 # true 1505 $perl_scalar = $json->utf8(1)->decode($str); 1506 # died because of 'Wide character in subroutine' 1507 1508 See to "A FEW NOTES ON UNICODE AND PERL" in JSON::XS. 1509 1510 $JSON::UnMapping 1511 Disable. See to MAPPING. 1512 1513 $JSON::SelfConvert 1514 This option was deleted. Instead of it, if a givien blessed object 1515 has the "TO_JSON" method, "TO_JSON" will be executed with 1516 "convert_blessed". 1517 1518 $json->convert_blessed->encode($bleesed_hashref_or_arrayref) 1519 # if need, call allow_blessed 1520 1521 Note that it was "toJson" in old version, but now not "toJson" but 1522 "TO_JSON". 1523 1524TODO 1525 example programs 1526 1527THREADS 1528 No test with JSON::PP. If with JSON::XS, See to "THREADS" in JSON::XS. 1529 1530BUGS 1531 Please report bugs relevant to "JSON" to <makamaka[at]cpan.org>. 1532 1533SEE ALSO 1534 Most of the document is copied and modified from JSON::XS doc. 1535 1536 JSON::XS, JSON::PP 1537 1538 "RFC4627"(<http://www.ietf.org/rfc/rfc4627.txt>) 1539 1540AUTHOR 1541 Makamaka Hannyaharamitu, <makamaka[at]cpan.org> 1542 1543 JSON::XS was written by Marc Lehmann <schmorp[at]schmorp.de> 1544 1545 The relese of this new version owes to the courtesy of Marc Lehmann. 1546 1547COPYRIGHT AND LICENSE 1548 Copyright 2005-2011 by Makamaka Hannyaharamitu 1549 1550 This library is free software; you can redistribute it and/or modify it 1551 under the same terms as Perl itself. 1552 1553