--- JSON-XS/XS.pm 2008/03/25 07:46:15 1.94 +++ JSON-XS/XS.pm 2009/02/18 00:08:28 1.117 @@ -1,9 +1,9 @@ =head1 NAME -=encoding utf-8 - JSON::XS - JSON serialising/deserialising, done correctly and fast +=encoding utf-8 + JSON::XS - 正しくて高速な JSON シリアライザ/デシリアライザ (http://fleur.hio.jp/perldoc/mix/lib/JSON/XS.html) @@ -39,7 +39,7 @@ Beginning with version 2.0 of the JSON module, when both JSON and JSON::XS are installed, then JSON will fall back on JSON::XS (this can be -overriden) with no overhead due to emulation (by inheritign constructor +overridden) with no overhead due to emulation (by inheriting constructor and methods). If JSON::XS is not available, it will fall back to the compatible JSON::PP module as backend, so using JSON instead of JSON::XS gives you a portable JSON API that can be fast when you need and doesn't @@ -51,8 +51,6 @@ their maintainers are unresponsive, gone missing, or not listening to bug reports for other reasons. -See COMPARISON, below, for a comparison to some other JSON modules. - See MAPPING, below, on how JSON::XS maps perl values to JSON values and vice versa. @@ -67,7 +65,7 @@ =item * round-trip integrity -When you serialise a perl data structure using only datatypes supported +When you serialise a perl data structure using only data types supported by JSON, the deserialised data structure is identical on the Perl level. (e.g. the string "2.0" doesn't suddenly become "2" just because it looks like a number). There minor I exceptions to this, read the MAPPING @@ -86,13 +84,13 @@ =item * simple to use -This module has both a simple functional interface as well as an objetc +This module has both a simple functional interface as well as an object oriented interface interface. =item * reasonably versatile output formats You can choose between the most compact guaranteed-single-line format -possible (nice for simple line-based protocols), a pure-ascii format +possible (nice for simple line-based protocols), a pure-ASCII format (for when your transport is not 8-bit clean, still supports the whole Unicode range), or a pretty-printed format (for when you want to read that stuff). Or you can combine those features in whatever way you like. @@ -103,9 +101,10 @@ package JSON::XS; +no warnings; use strict; -our $VERSION = '2.1'; +our $VERSION = '2.232'; our @ISA = qw(Exporter); our @EXPORT = qw(encode_json decode_json to_json from_json); @@ -139,7 +138,7 @@ $json_text = JSON::XS->new->utf8->encode ($perl_scalar) -except being faster. +Except being faster. =item $perl_scalar = decode_json $json_text @@ -151,7 +150,7 @@ $perl_scalar = JSON::XS->new->utf8->decode ($json_text) -except being faster. +Except being faster. =item $is_boolean = JSON::XS::is_bool $scalar @@ -199,7 +198,7 @@ exist. =item 4. A "Unicode String" is simply a string where each character can be -validly interpreted as a Unicode codepoint. +validly interpreted as a Unicode code point. If you have UTF-8 encoded data, it is no longer a Unicode string, but a Unicode string encoded in UTF-8, giving you a binary string. @@ -465,6 +464,22 @@ JSON::XS->new->allow_nonref->encode ("Hello, World!") => "Hello, World!" +=item $json = $json->allow_unknown ([$enable]) + +=item $enabled = $json->get_allow_unknown + +If C<$enable> is true (or missing), then C will I throw an +exception when it encounters values it cannot represent in JSON (for +example, filehandles) but instead will encode a JSON C value. Note +that blessed objects are not included here and are handled separately by +c. + +If C<$enable> is false (the default), then C will throw an +exception when it encounters anything it cannot encode as JSON. + +This option does not affect C in any way, and it is recommended to +leave it off unless you know your communications partner. + =item $json = $json->allow_blessed ([$enable]) =item $enabled = $json->get_allow_blessed @@ -614,9 +629,9 @@ =item $max_depth = $json->get_max_depth Sets the maximum nesting level (default C<512>) accepted while encoding -or decoding. If the JSON text or Perl data structure has an equal or -higher nesting level then this limit, then the encoder and decoder will -stop and croak at that point. +or decoding. If a higher nesting level is detected in JSON text or a Perl +data structure, then the encoder and decoder will stop and croak at that +point. Nesting level is defined by number of hash- or arrayrefs that the encoder needs to traverse to reach a given point or the number of C<{> or C<[> @@ -626,9 +641,12 @@ Setting the maximum depth to one disallows any nesting, so that ensures that the object is only a single hash/object or array. -The argument to C will be rounded up to the next highest power -of two. If no argument is given, the highest possible setting will be -used, which is rarely useful. +If no argument is given, the highest possible setting will be used, which +is rarely useful. + +Note that nesting is implemented by recursion in C. The default value has +been chosen to be as large as typical operating systems allow without +crashing. See SECURITY CONSIDERATIONS, below, for more info on why this is useful. @@ -638,13 +656,12 @@ Set the maximum length a JSON text may have (in bytes) where decoding is being attempted. The default is C<0>, meaning no limit. When C -is called on a string longer then this number of characters it will not +is called on a string that is longer then this many bytes, it will not attempt to decode the string but throw an exception. This setting has no effect on C (yet). -The argument to C will be rounded up to the next B -power of two (so may be more than requested). If no argument is given, the -limit check will be deactivated (same as when C<0> is specified). +If no argument is given, the limit check will be deactivated (same as when +C<0> is specified). See SECURITY CONSIDERATIONS, below, for more info on why this is useful. @@ -685,19 +702,25 @@ =head1 INCREMENTAL PARSING -[This section is still EXPERIMENTAL] - In some cases, there is the need for incremental parsing of JSON texts. While this module always has to keep both JSON text and resulting Perl data structure in memory at one time, it does allow you to parse a JSON stream incrementally. It does so by accumulating text until it has a full JSON object, which it then can decode. This process is similar to -using C to see if a full JSON object is available, but is -much more efficient (JSON::XS will only attempt to parse the JSON text -once it is sure it has enough text to get a decisive result, using a very -simple but truly incremental parser). +using C to see if a full JSON object is available, but +is much more efficient (and can be implemented with a minimum of method +calls). + +JSON::XS will only attempt to parse the JSON text once it is sure it +has enough text to get a decisive result, using a very simple but +truly incremental parser. This means that it sometimes won't stop as +early as the full parser, for example, it doesn't detect parenthese +mismatches. The only thing it guarantees is that it starts decoding as +soon as a syntactically valid JSON text has been seen. This means you need +to set resource limits (e.g. C) to ensure the parser will stop +parsing in the presence if syntax errors. -The following two methods deal with this. +The following methods implement this incremental parser. =over 4 @@ -716,13 +739,18 @@ If the method is called in scalar context, then it will try to extract exactly I JSON object. If that is successful, it will return this -object, otherwise it will return C. This is the most common way of +object, otherwise it will return C. If there is a parse error, +this method will croak just as C would do (one can then use +C to skip the errornous part). This is the most common way of using the method. And finally, in list context, it will try to extract as many objects from the stream as it can find and return them, or the empty list otherwise. For this to work, there must be no separators between the JSON -objects or arrays, instead they must be concatenated back-to-back. +objects or arrays, instead they must be concatenated back-to-back. If +an error occurs, an exception will be raised as in the scalar context +case. Note that in this case, any previously-parsed JSON texts will be +lost. =item $lvalue_string = $json->incr_text @@ -738,6 +766,26 @@ JSON object or b) parsing multiple JSON objects separated by non-JSON text (such as commas). +=item $json->incr_skip + +This will reset the state of the incremental parser and will remove +the parsed text from the input buffer so far. This is useful after +C died, in which case the input buffer and incremental parser +state is left unchanged, to skip the text parsed so far and to reset the +parse state. + +The difference to C is that only text until the parse error +occured is removed. + +=item $json->incr_reset + +This completely resets the incremental parser, that is, after this call, +it will be as if the parser had never parsed anything. + +This is useful if you want to repeatedly parse JSON objects and want to +ignore any trailing data, which means you have to reset the parser after +each successful decode. + =back =head2 LIMITATIONS @@ -987,7 +1035,7 @@ C<1>, which get turned into C and C atoms in JSON. You can also use C and C to improve readability. - encode_json [\0,JSON::XS::true] # yields [false,true] + encode_json [\0, JSON::XS::true] # yields [false,true] =item JSON::XS::true, JSON::XS::false @@ -1139,102 +1187,69 @@ =back -=head1 COMPARISON - -As already mentioned, this module was created because none of the existing -JSON modules could be made to work correctly. First I will describe the -problems (or pleasures) I encountered with various existing JSON modules, -followed by some benchmark values. JSON::XS was designed not to suffer -from any of these problems or limitations. - -=over 4 - -=item JSON 2.xx - -A marvellous piece of engineering, this module either uses JSON::XS -directly when available (so will be 100% compatible with it, including -speed), or it uses JSON::PP, which is basically JSON::XS translated to -Pure Perl, which should be 100% compatible with JSON::XS, just a bit -slower. - -You cannot really lose by using this module, especially as it tries very -hard to work even with ancient Perl versions, while JSON::XS does not. - -=item JSON 1.07 - -Slow (but very portable, as it is written in pure Perl). +=head2 JSON and ECMAscript -Undocumented/buggy Unicode handling (how JSON handles Unicode values is -undocumented. One can get far by feeding it Unicode strings and doing -en-/decoding oneself, but Unicode escapes are not working properly). +JSON syntax is based on how literals are represented in javascript (the +not-standardised predecessor of ECMAscript) which is presumably why it is +called "JavaScript Object Notation". -No round-tripping (strings get clobbered if they look like numbers, e.g. -the string C<2.0> will encode to C<2.0> instead of C<"2.0">, and that will -decode into the number 2. +However, JSON is not a subset (and also not a superset of course) of +ECMAscript (the standard) or javascript (whatever browsers actually +implement). -=item JSON::PC 0.01 +If you want to use javascript's C function to "parse" JSON, you +might run into parse errors for valid JSON texts, or the resulting data +structure might not be queryable: -Very fast. +One of the problems is that U+2028 and U+2029 are valid characters inside +JSON strings, but are not allowed in ECMAscript string literals, so the +following Perl fragment will not output something that can be guaranteed +to be parsable by javascript's C: -Undocumented/buggy Unicode handling. + use JSON::XS; -No round-tripping. + print encode_json [chr 0x2028]; -Has problems handling many Perl values (e.g. regex results and other magic -values will make it croak). +The right fix for this is to use a proper JSON parser in your javascript +programs, and not rely on C (see for example Douglas Crockford's +F parser). -Does not even generate valid JSON (C<{1,2}> gets converted to C<{1:2}> -which is not a valid JSON text. +If this is not an option, you can, as a stop-gap measure, simply encode to +ASCII-only JSON: -Unmaintained (maintainer unresponsive for many months, bugs are not -getting fixed). + use JSON::XS; -=item JSON::Syck 0.21 + print JSON::XS->new->ascii->encode ([chr 0x2028]); -Very buggy (often crashes). +Note that this will enlarge the resulting JSON text quite a bit if you +have many non-ASCII characters. You might be tempted to run some regexes +to only escape U+2028 and U+2029, e.g.: -Very inflexible (no human-readable format supported, format pretty much -undocumented. I need at least a format for easy reading by humans and a -single-line compact format for use in a protocol, and preferably a way to -generate ASCII-only JSON texts). + # DO NOT USE THIS! + my $json = JSON::XS->new->utf8->encode ([chr 0x2028]); + $json =~ s/\xe2\x80\xa8/\\u2028/g; # escape U+2028 + $json =~ s/\xe2\x80\xa9/\\u2029/g; # escape U+2029 + print $json; -Completely broken (and confusingly documented) Unicode handling (Unicode -escapes are not working properly, you need to set ImplicitUnicode to -I values on en- and decoding to get symmetric behaviour). +Note that I: the above only works for U+2028 and +U+2029 and thus only for fully ECMAscript-compliant parsers. Many existing +javascript implementations, however, have issues with other characters as +well - using C naively simply I cause problems. -No round-tripping (simple cases work, but this depends on whether the scalar -value was used in a numeric context or not). +Another problem is that some javascript implementations reserve +some property names for their own purposes (which probably makes +them non-ECMAscript-compliant). For example, Iceweasel reserves the +C<__proto__> property name for it's own purposes. -Dumping hashes may skip hash values depending on iterator state. +If that is a problem, you could parse try to filter the resulting JSON +output for these property strings, e.g.: -Unmaintained (maintainer unresponsive for many months, bugs are not -getting fixed). + $json =~ s/"__proto__"\s*:/"__proto__renamed":/g; -Does not check input for validity (i.e. will accept non-JSON input and -return "something" instead of raising an exception. This is a security -issue: imagine two banks transferring money between each other using -JSON. One bank might parse a given non-JSON request and deduct money, -while the other might reject the transaction with a syntax error. While a -good protocol will at least recover, that is extra unnecessary work and -the transaction will still not succeed). +This works because C<__proto__> is not valid outside of strings, so every +occurence of C<"__proto__"\s*:> must be a string used as property name. -=item JSON::DWIW 0.04 - -Very fast. Very natural. Very nice. - -Undocumented Unicode handling (but the best of the pack. Unicode escapes -still don't get parsed properly). - -Very inflexible. - -No round-tripping. - -Does not generate valid JSON texts (key strings are often unquoted, empty keys -result in nothing being output) - -Does not check input for validity. - -=back +If you know of other incompatibilities, please let me know. =head2 JSON and YAML @@ -1302,8 +1317,9 @@ a very short single-line JSON string (also available at L). - {"method": "handleMessage", "params": ["user1", "we were just talking"], \ - "id": null, "array":[1,11,234,-5,1e5,1e7, true, false]} + {"method": "handleMessage", "params": ["user1", + "we were just talking"], "id": null, "array":[1,11,234,-5,1e5,1e7, + true, false]} It shows the number of encodes/decodes per second (JSON::XS uses the functional interface, while JSON::XS/2 uses the OO interface @@ -1411,9 +1427,8 @@ =head1 BUGS While the goal of this module is to be correct, that unfortunately does -not mean it's bug-free, only that I think its design is bug-free. It is -still relatively early in its development. If you keep reporting bugs they -will be fixed swiftly, though. +not mean it's bug-free, only that I think its design is bug-free. If you +keep reporting bugs they will be fixed swiftly, though. Please refrain from using rt.cpan.org or any other bug reporting service. I put the contact address into my modules for a reason.