JSON::PP was earlier included in the JSON distribution, but has since Perl 5.14 been a core module. For this reason, JSON::PP was removed from the JSON distribution and can now be found also in the Perl5 repository at

************************** CAUTION ********************************
* This is 'JSON module version 2' and there are many differences *
* to version 1.xx *
* Please check your applications using old version. *
* See to 'INCOMPATIBLE CHANGES TO OLD VERSION' *
*******************************************************************

This module converts Perl data structures to JSON and vice versa using either JSON::XS or JSON::PP.

JSON::XS is the fastest and most proper JSON module on CPAN which must be compiled and installed in your environment. JSON::PP is a pure-Perl module which is bundled in this distribution and has a strong compatibility to JSON::XS.

This module try to use JSON::XS by default and fail to it, use JSON::PP instead. So its features completely depend on JSON::XS or JSON::PP.

This module (i.e. backend modules) knows how to handle Unicode, documents how and when it does so, and even documents what "correct" means.

Even though there are limitations, this feature is available since Perl version 5.6.

JSON::XS requires Perl 5.8.2 (but works correctly in 5.8.8 or later), so in older versions JSON should call JSON::PP as the backend which can be used since Perl 5.005.

With Perl 5.8.x JSON::PP works, but from 5.8.0 to 5.8.2, because of a Perl side problem, JSON::PP works slower in the versions. And in 5.005, the Unicode handling is not available. See to "UNICODE HANDLING ON PERLS" in JSON::PP for more information.

When you serialise a perl data structure using only data types supported by JSON and Perl, 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 are minor exceptions to this, read the "MAPPING" section below to learn about those.

strict checking of JSON correctness

There is no guessing, no generating of illegal JSON texts by default, and only JSON is accepted as input by default (the latter is a security feature).

This module returns a JSON::XS object itself if available. Compared to other JSON modules and other serialisers such as Storable, JSON::XS usually compares favorably in terms of speed, too.

If not available, JSON returns a JSON::PP object instead of JSON::XS and it is very slow as pure-Perl.

simple to use

This module has both a simple functional interface as well as an object oriented interface interface.

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 (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.

If you know a JSON text from an outer world - a network, a file content, and so on, is encoded in UTF-8, you should use decode_json or JSON module object with utf8 enable. And the decoded result will contain UNICODE characters.

In this case, $unicode_json_text is of course UNICODE string. So you cannot use decode_json nor JSON module object with utf8 enable. Instead of them, you use JSON module object with utf8 disable or from_json.

If $perl_scalar does not contain UNICODE but $encoding-encoded strings for some reason, then its characters are regarded as latin1 for perl (because it does not concern with your $encoding). You cannot use encode_json nor JSON module object with utf8 enable. Instead of them, you use JSON module object with utf8 disable or to_json. Note that the resulted text is a UNICODE string but no problem to print it.

If $enable is true (or missing), then the encode method will not generate characters outside the code range 0..127. Any Unicode characters outside that range will be escaped using either a single \uXXXX or a double \uHHHH\uLLLLL escape sequence, as per RFC4627.

If $enable is false, then the encode method will not escape Unicode characters unless required by the JSON syntax or other flags. This results in a faster and more compact format.

If $enable is true (or missing), then the encode method will encode the JSON result into UTF-8, as required by many protocols, while the decode method expects to be handled an UTF-8-encoded string. Please note that UTF-8-encoded strings do not contain any characters outside the range 0..255, they are thus useful for bytewise/binary I/O.

In future versions, enabling this option might enable autodetection of the UTF-16 and UTF-32 encoding families, as described in RFC4627.

If $enable is false, then the encode method will return the JSON string as a (non-encoded) Unicode string, while decode expects thus a Unicode string. Any decoding or encoding (e.g. to UTF-8 or UTF-16) needs to be done yourself, e.g. using the Encode module.

If $enable is true (or missing), then the encode method will add an extra optional space after the : separating keys from values in JSON objects and extra whitespace after the , separating key-value pairs and array members.

If $enable is false, then the encode method will not add any extra space at those places.

If $enable is true (or missing), then decode will accept some extensions to normal JSON syntax (see below). encode will not be affected in anyway. Be aware that this option makes you accept invalid JSON texts as if they were valid!. I suggest only to use this option to parse application-specific files written by humans (configuration files, resource files etc.)

If $enable is false (the default), then decode will only accept valid JSON texts.

Currently accepted extensions are:

list items can have an end-comma

JSON separates array elements and key-value pairs with commas. This can be annoying if you write JSON texts manually and want to be able to quickly append elements, so this extension accepts comma at the end of such items not just between them:

Whenever JSON allows whitespace, shell-style comments are additionally allowed. They are terminated by the first carriage-return or line-feed character, after which more white-space and comments are allowed.

If $enable is true (or missing), then the encode method will output JSON objects by sorting their keys. This is adding a comparatively high overhead.

If $enable is false, then the encode method will output key-value pairs in the order Perl stores them (which will likely change between runs of the same script).

This option is useful if you want the same data structure to be encoded as the same JSON text (given the same overall settings). If it is disabled, the same hash might be encoded differently even if contains the same data, as key-value pairs have no inherent ordering in Perl.

If $enable is true (or missing), then the encode method can convert a non-reference into its corresponding string, number or null JSON value, which is an extension to RFC4627. Likewise, decode will accept those JSON values instead of croaking.

If $enable is false, then the encode method will croak if it isn't passed an arrayref or hashref, as JSON texts must either be an object or array. Likewise, decode will croak if given something that is not a JSON object or array.

If $enable is true (or missing), then "encode" will *not* throw an exception when it encounters values it cannot represent in JSON (for example, filehandles) but instead will encode a JSON "null" value. Note that blessed objects are not included here and are handled separately by c<allow_nonref>.

If $enable is false (the default), then "encode" will throw an exception when it encounters anything it cannot encode as JSON.

This option does not affect "decode" in any way, and it is recommended to leave it off unless you know your communications partner.

If $enable is true (or missing), then the encode method will not barf when it encounters a blessed reference. Instead, the value of the convert_blessed option will decide whether null (convert_blessed disabled or no TO_JSON method found) or a representation of the object (convert_blessed enabled and TO_JSON method found) is being encoded. Has no effect on decode.

If $enable is false (the default), then encode will throw an exception when it encounters a blessed object.

If $enable is true (or missing), then encode, upon encountering a blessed object, will check for the availability of the TO_JSON method on the object's class. If found, it will be called in scalar context and the resulting scalar will be encoded instead of the object. If no TO_JSON method is found, the value of allow_blessed will decide what to do.

The TO_JSON method may safely call die if it wants. If TO_JSON returns other blessed objects, those will be handled in the same way. TO_JSON must take care of not causing an endless recursion cycle (== crash) in this case. The name of TO_JSON was chosen because other methods called by the Perl core (== not by the user of the object) are usually in upper case letters and to avoid collisions with the to_json function or method.

This setting does not yet influence decode in any way.

If $enable is false, then the allow_blessed setting will decide what to do when a blessed object is found.

When $coderef is specified, it will be called from decode each time it decodes a JSON object. The only argument passed to the coderef is a reference to the newly-created hash. If the code references returns a single scalar (which need not be a reference), this value (i.e. a copy of that scalar to avoid aliasing) is inserted into the deserialised data structure. If it returns an empty list (NOTE: notundef, which is a valid scalar), the original deserialised hash will be inserted. This setting can slow down decoding considerably.

When $coderef is omitted or undefined, any existing callback will be removed and decode will not change the deserialised hash in any way.

Works remotely similar to filter_json_object, but is only called for JSON objects having a single key named $key.

This $coderef is called before the one specified via filter_json_object, if any. It gets passed the single value in the JSON object. If it returns a single value, it will be inserted into the data structure. If it returns nothing (not even undef but the empty list), the callback from filter_json_object will be called next, as if no single-key callback were specified.

If $coderef is omitted or undefined, the corresponding callback will be disabled. There can only ever be one callback for a given key.

As this callback gets called less often then the filter_json_object one, decoding speed will not usually suffer as much. Therefore, single-key objects make excellent targets to serialise Perl objects into, especially as single-key JSON objects are as close to the type-tagged value concept as JSON gets (it's basically an ID/VALUE tuple). Of course, JSON does not support this in any way, so you need to make sure your data never looks like a serialised Perl hash.

Typical names for the single object key are __class_whatever__, or $__dollars_are_rarely_used__$ or }ugly_brace_placement, or even things like __class_md5sum(classname)__, to reduce the risk of clashing with real hashes.

With JSON::XS, this flag resizes strings generated by either encode or decode 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 (and some buggy Perl or C code might even rely on that internal representation being used).

With JSON::PP, it is noop about resizing strings but tries utf8::downgrade to the returned string by encode. See to utf8.

Sets the maximum nesting level (default 512) accepted while encoding 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 { or [ characters without their matching closing parenthesis crossed to reach a given character in a string.

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. (JSON::XS)

With JSON::PP as the backend, when a large value (100 or more) was set and it de/encodes a deep nested object/text, it may raise a warning 'Deep recursion on subroutine' at the perl runtime phase.

Set the maximum length a JSON text may have (in bytes) where decoding is being attempted. The default is 0, meaning no limit. When decode 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 encode (yet).

If no argument is given, the limit check will be deactivated (same as when 0 is specified).

Converts the given Perl data structure (a simple scalar or a reference to a hash or array) to its JSON representation. Simple scalars will be converted into JSON string or number sequences, while references to arrays become JSON arrays and references to hashes become JSON objects. Undefined Perl values (e.g. undef) become JSON null values. References to the integers 0 and 1 are converted into true and false.

This works like the decode 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.

In some cases, there is the need for incremental parsing of JSON texts. This module 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 decode_prefix to see if a full JSON object is available, but is much more efficient (and can be implemented with a minimum of method calls).

The backend module 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 parenthesis 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. max_size) to ensure the parser will stop parsing in the presence if syntax errors.

This is the central parsing function. It can both append new text and extract objects from the stream accumulated so far (both of these functions are optional).

If $string is given, then this string is appended to the already existing JSON fragment stored in the $json object.

After that, if the function is called in void context, it will simply return without doing anything further. This can be used to add more text in as many chunks as you want.

If the method is called in scalar context, then it will try to extract exactly one JSON object. If that is successful, it will return this object, otherwise it will return undef. If there is a parse error, this method will croak just as decode would do (one can then use incr_skip to skip the erroneous 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. 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.

Example: Parse some JSON arrays/objects in a given string and return them.

This method returns the currently stored JSON fragment as an lvalue, that is, you can manipulate it. This only works when a preceding call to incr_parse in scalar context successfully returned an object. Under all other circumstances you must not call this function (I mean it. although in simple tests it might actually work, it will fail under real world conditions). As a special exception, you can also call this method before having parsed anything.

This function is useful in two cases: a) finding the trailing text after a JSON object or b) parsing multiple JSON objects separated by non-JSON text (such as commas).

$json->incr_text =~ s/\s*,\s*//;

In Perl 5.005, lvalue attribute is not available. You must write codes like the below:

This will reset the state of the incremental parser and will remove the parsed text from the input buffer. This is useful after incr_parse 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 unescaped [\x00-\x1f\x22\x2f\x5c] strings are invalid in JSON strings and the module doesn't allow to decode to these (except for \x2f). If $enable is true (or missing), then decode will accept these unescaped strings.

A JSON number becomes either an integer, numeric (floating point) or string scalar in perl, depending on its range and any fractional parts. On the Perl level, there is no difference between those as Perl handles all the conversion details, but an integer may take slightly less memory and might represent more values exactly than floating point numbers.

If the number consists of digits only, JSON will try to represent it as an integer value. If that fails, it will try to represent it as a numeric (floating point) value if that is possible without loss of precision. Otherwise it will preserve the number as a string value (in which case you lose roundtripping ability, as the JSON number will be re-encoded to a JSON string).

Numbers containing a fractional or exponential part will always be represented as numeric (floating point) values, possibly at a loss of precision (in which case you might lose perfect roundtripping ability, but the JSON number will still be re-encoded as a JSON number).

Note that precision is not accuracy - binary floating point values cannot represent most decimal fractions exactly, and when converting from and to floating point, JSON only guarantees precision up to but not including the least significant bit.

If the backend is JSON::PP and allow_bignum is enable, the big integers and the numeric can be optionally converted into Math::BigInt and Math::BigFloat objects.

These JSON atoms become JSON::true and JSON::false, respectively. They are overloaded to act almost exactly like the numbers 1 and 0. You can check whether a scalar is a JSON boolean by using the JSON::is_bool function.

If JSON::true and JSON::false are used as strings or compared as strings, they represent as true and false respectively.

Perl hash references become JSON objects. As there is no inherent ordering 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 optionally sort the hash keys (determined by the canonical flag), so the same data structure 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.

In future, the ordered object feature will be added to JSON::PP using tie mechanism.

Other unblessed references are generally not allowed and will cause an exception to be thrown, except for references to the integers 0 and 1, which get turned into false and true atoms in JSON. You can also use JSON::false and JSON::true to improve readability.

Blessed objects are not directly representable in JSON. See the allow_blessed and convert_blessed methods on various options on how to deal with this: basically, you can choose between throwing an exception, encoding the reference as if it weren't blessed, or provide your own serialiser method.

Simple Perl scalars (any scalar that is not a reference) are the most difficult objects to encode: JSON::XS and JSON::PP will encode undefined scalars as JSON null values, scalars that have last been used in a string context before encoding as JSON strings, and anything else as number value:

my $x = "3"; # some variable containing a string
$x += 0; # numify it, ensuring it will be dumped as a number
$x *= 1; # same thing, the choice is yours.

You can not currently force the type in other, less obscure, ways.

Note that numerical precision has the same meaning as under Perl (so binary to decimal conversion follows the same rules as in Perl, which can differ to other languages). Also, your perl interpreter might expose extensions to the floating point numbers of your platform, such as infinities or NaN's - these cannot be represented in JSON, and it is an error to pass those in.

At this time, the returned object is a JSON::Backend::XS::Supportable object (re-blessed XS object), and by checking JSON::XS unsupported flags in de/encoding, can support some unsupported methods - loose, allow_bignum, allow_barekey, allow_singlequote, escape_slash and indent_length.

When any unsupported methods are not enable, XS de/encode will be used as is. The switch is achieved by changing the symbolic tables.

-support_by_pp is effective only when the backend module is JSON::XS and it makes the de/encoding speed down a bit.

Perl implementation of JSON-RPC protocol - JSONRPC , JSONRPC::Transport::HTTP and Apache::JSONRPC are deleted in this distribution. Instead of them, there is JSON::RPC which supports JSON-RPC protocol version 1.1.