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