--- JSON-XS/XS.pm 2007/03/24 22:57:12 1.19 +++ JSON-XS/XS.pm 2007/05/09 16:33:53 1.34 @@ -6,12 +6,17 @@ use JSON::XS; - # exported functions, croak on error + # exported functions, they croak on error + # and expect/generate UTF-8 $utf8_encoded_json_text = to_json $perl_hash_or_arrayref; $perl_hash_or_arrayref = from_json $utf8_encoded_json_text; - # oo-interface + # objToJson and jsonToObj aliases to to_json and from_json + # are exported for compatibility to the JSON module, + # but should not be used in new code. + + # OO-interface $coder = JSON::XS->new->ascii->pretty->allow_nonref; $pretty_printed_unencoded = $coder->encode ($perl_scalar); @@ -38,7 +43,7 @@ =over 4 -=item * correct handling of unicode issues +=item * correct unicode handling This module knows how to handle Unicode, and even documents how and when it does so. @@ -47,7 +52,8 @@ When you serialise a perl data structure using only datatypes supported by JSON, the deserialised data structure is identical on the Perl level. -(e.g. the string "2.0" doesn't suddenly become "2"). +(e.g. the string "2.0" doesn't suddenly become "2" just because it looks +like a number). =item * strict checking of JSON correctness @@ -68,10 +74,10 @@ =item * reasonably versatile output formats You can choose between the most compact guarenteed single-line format -possible (nice for simple line-based protocols), a pure-ascii format (for -when your transport is not 8-bit clean), or a pretty-printed format (for -when you want to read that stuff). Or you can combine those features in -whatever way you like. +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. =back @@ -79,11 +85,13 @@ package JSON::XS; +use strict; + BEGIN { - $VERSION = '0.7'; - @ISA = qw(Exporter); + our $VERSION = '1.2'; + our @ISA = qw(Exporter); - @EXPORT = qw(to_json from_json); + our @EXPORT = qw(to_json from_json objToJson jsonToObj); require Exporter; require XSLoader; @@ -123,6 +131,7 @@ =back + =head1 OBJECT-ORIENTED INTERFACE The object oriented interface lets you configure your own encoding or @@ -147,15 +156,44 @@ generate characters outside the code range C<0..127> (which is ASCII). Any unicode characters outside that range will be escaped using either a single \uXXXX (BMP characters) or a double \uHHHH\uLLLLL escape sequence, -as per RFC4627. +as per RFC4627. The resulting encoded JSON text can be treated as a native +unicode string, an ascii-encoded, latin1-encoded or UTF-8 encoded string, +or any other superset of ASCII. If C<$enable> is false, then the C method will not escape Unicode -characters unless required by the JSON syntax. This results in a faster -and more compact format. +characters unless required by the JSON syntax or other flags. This results +in a faster and more compact format. + +The main use for this flag is to produce JSON texts that can be +transmitted over a 7-bit channel, as the encoded JSON texts will not +contain any 8 bit characters. JSON::XS->new->ascii (1)->encode ([chr 0x10401]) => ["\ud801\udc01"] +=item $json = $json->latin1 ([$enable]) + +If C<$enable> is true (or missing), then the C method will encode +the resulting JSON text as latin1 (or iso-8859-1), escaping any characters +outside the code range C<0..255>. The resulting string can be treated as a +latin1-encoded JSON text or a native unicode string. The C method +will not be affected in any way by this flag, as C by default +expects unicode, which is a strict superset of latin1. + +If C<$enable> is false, then the C method will not escape Unicode +characters unless required by the JSON syntax or other flags. + +The main use for this flag is efficiently encoding binary data as JSON +text, as most octets will not be escaped, resulting in a smaller encoded +size. The disadvantage is that the resulting JSON text is encoded +in latin1 (and must correctly be treated as such when storing and +transfering), a rare encoding for JSON. It is therefore most useful when +you want to store data structures known to contain binary data efficiently +in files or databases, not when talking to other JSON encoders/decoders. + + JSON::XS->new->latin1->encode (["\x{89}\x{abc}"] + => ["\x{89}\\u0abc"] # (perl syntax, U+abc escaped, U+89 not) + =item $json = $json->utf8 ([$enable]) If C<$enable> is true (or missing), then the C method will encode @@ -277,16 +315,21 @@ =item $json = $json->shrink ([$enable]) Perl usually over-allocates memory a bit when allocating space for -strings. This flag optionally resizes strings generated by either +strings. This flag optionally resizes strings generated by either C or C to their minimum size possible. This can save memory when your JSON texts are either very very long or you have many short strings. It will also try to downgrade any strings to octet-form if possible: perl stores strings internally either in an encoding called UTF-X or in octet-form. The latter cannot store everything but uses less -space in general. +space in general (and some buggy Perl or C code might even rely on that +internal representation being used). + +The actual definition of what shrink does might change in future versions, +but it will always try to save space at the expense of time. -If C<$enable> is true (or missing), the string returned by C will be shrunk-to-fit, -while all strings generated by C will also be shrunk-to-fit. +If C<$enable> is true (or missing), the string returned by C will +be shrunk-to-fit, while all strings generated by C will also be +shrunk-to-fit. If C<$enable> is false, then the normal perl allocation algorithms are used. If you work with your data, then this is likely to be faster. @@ -295,6 +338,26 @@ strings that look like integers or floats into integers or floats internally (there is no difference on the Perl level), saving space. +=item $json = $json->max_depth ([$maximum_nesting_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. + +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<[> +characters without their matching closing parenthesis crossed to reach a +given character in a string. + +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 nearest power +of two. + +See SECURITY CONSIDERATIONS, below, for more info on why this is useful. + =item $json_text = $json->encode ($perl_scalar) Converts the given Perl data structure (a simple scalar or a reference @@ -313,8 +376,23 @@ Perl arrayrefs and JSON objects become Perl hashrefs. C becomes C<1>, C becomes C<0> and C becomes C. +=item ($perl_scalar, $characters) = $json->decode_prefix ($json_text) + +This works like the C method, but instead of raising an exception +when there is trailing garbage after the first JSON object, it will +silently stop parsing there and return the number of characters consumed +so far. + +This is useful if your JSON texts are not delimited by an outer protocol +(which is not the brightest thing to do in the first place) and you need +to know where the JSON text ends. + + JSON::XS->new->decode_prefix ("[1] the tail") + => ([], 3) + =back + =head1 MAPPING This section describes how JSON::XS maps Perl values to JSON values and @@ -377,17 +455,28 @@ =item hash references Perl hash references become JSON objects. As there is no inherent ordering -in hash keys, they will usually be encoded in a pseudo-random order that -can change between runs of the same program but stays generally the same -within a single run of a program. JSON::XS can optionally sort the hash -keys (determined by the I flag), so the same datastructure -will serialise to the same JSON text (given same settings and version of -JSON::XS), but this incurs a runtime overhead. +in hash keys (or JSON objects), they will usually be encoded in a +pseudo-random order that can change between runs of the same program but +stays generally the same within a single run of a program. JSON::XS can +optionally sort the hash keys (determined by the I flag), so +the same datastructure will serialise to the same JSON text (given same +settings and version of JSON::XS), but this incurs a runtime overhead +and is only rarely useful, e.g. when you want to compare some JSON text +against another for equality. =item array references Perl array references become JSON arrays. +=item other references + +Other unblessed references are generally not allowed and will cause an +exception to be thrown, except for references to the integers C<0> and +C<1>, which get turned into C and C atoms in JSON. You can +also use C and C to improve readability. + + to_json [\0,JSON::XS::true] # yields [false,true] + =item blessed objects Blessed objects are not allowed. JSON::XS currently tries to encode their @@ -429,12 +518,9 @@ You can not currently output JSON booleans or force the type in other, less obscure, ways. Tell me if you need this capability. -=item circular data structures - -Those will be encoded until memory or stackspace runs out. - =back + =head1 COMPARISON As already mentioned, this module was created because none of the existing @@ -572,22 +658,49 @@ to decode or encode properly, so it was impossible to prepare a fair comparison table for that case. -=head1 RESOURCE LIMITS -JSON::XS does not impose any limits on the size of JSON texts or Perl -values they represent - if your machine can handle it, JSON::XS will -encode or decode it. Future versions might optionally impose structure -depth and memory use resource limits. +=head1 SECURITY CONSIDERATIONS + +When you are using JSON in a protocol, talking to untrusted potentially +hostile creatures requires relatively few measures. + +First of all, your JSON decoder should be secure, that is, should not have +any buffer overflows. Obviously, this module should ensure that and I am +trying hard on making that true, but you never know. + +Second, you need to avoid resource-starving attacks. That means you should +limit the size of JSON texts you accept, or make sure then when your +resources run out, thats just fine (e.g. by using a separate process that +can crash safely). The size of a JSON text in octets or characters is +usually a good indication of the size of the resources required to decode +it into a Perl structure. + +Third, JSON::XS recurses using the C stack when decoding objects and +arrays. The C stack is a limited resource: for instance, on my amd64 +machine with 8MB of stack size I can decode around 180k nested arrays but +only 14k nested JSON objects (due to perl itself recursing deeply on croak +to free the temporary). If that is exceeded, the program crashes. to be +conservative, the default nesting limit is set to 512. If your process +has a smaller stack, you should adjust this setting accordingly with the +C method. + +And last but least, something else could bomb you that I forgot to think +of. In that case, you get to keep the pieces. I am always open for hints, +though... + =head1 BUGS While the goal of this module is to be correct, that unfortunately does not mean its bug-free, only that I think its design is bug-free. It is -still very young and not well-tested. If you keep reporting bugs they will -be fixed swiftly, though. +still relatively early in its development. If you keep reporting bugs they +will be fixed swiftly, though. =cut +sub true() { \1 } +sub false() { \0 } + 1; =head1 AUTHOR