.... Set up some character translations and predefined strings. \*(-- will
This version is compatible with \s-1JSON::XS\s0 2.34 and later.
(The newest \s-1JSON::PP\s0 version still exists in \s-1CPAN\s0.)
Instead, the \*(C`JSON\*(C' distribution will include JSON::backportPP for backwards computability. \s-1JSON\s0.pm should thus work as it did before.
\s-1JSON\s0 (JavaScript Object Notation) is a simple data format. See to <http://www.json.org/> and \*(C`RFC4627\*(C'(<http://www.ietf.org/rfc/rfc4627.txt>).
This module converts Perl data structures to \s-1JSON\s0 and vice versa using either \s-1JSON::XS\s0 or \s-1JSON::PP\s0.
\s-1JSON::XS\s0 is the fastest and most proper \s-1JSON\s0 module on \s-1CPAN\s0 which must be compiled and installed in your environment. \s-1JSON::PP\s0 is a pure-Perl module which is bundled in this distribution and has a strong compatibility to \s-1JSON::XS\s0.
This module try to use \s-1JSON::XS\s0 by default and fail to it, use \s-1JSON::PP\s0 instead. So its features completely depend on \s-1JSON::XS\s0 or \s-1JSON::PP\s0.
See to \*(L"\s-1BACKEND\s0 \s-1MODULE\s0 \s-1DECISION\s0\*(R".
To distinguish the module name '\s-1JSON\s0' and the format type \s-1JSON\s0, the former is quoted by C<> (its results vary with your using media), and the latter is left just as it is.
Module name : \*(C`JSON\*(C'
Format type : \s-1JSON\s0
Converts the given Perl data structure to a \s-1UTF-8\s0 encoded, binary string.
This function call is functionally identical to:
.Vb 1 $json_text = JSON->new->utf8->encode($perl_scalar) .Ve
The opposite of \*(C`encode_json\*(C': expects an \s-1UTF-8\s0 (binary) string and tries to parse that as an \s-1UTF-8\s0 encoded \s-1JSON\s0 text, returning the resulting reference.
This function call is functionally identical to:
.Vb 1 $perl_scalar = JSON->new->utf8->decode($json_text) .Ve
Converts the given Perl data structure to a json string.
This function call is functionally identical to:
.Vb 1 $json_text = JSON->new->encode($perl_scalar) .Ve
Takes a hash reference as the second.
.Vb 1 $json_text = to_json($perl_scalar, $flag_hashref) .Ve
So,
.Vb 1 $json_text = to_json($perl_scalar, {utf8 => 1, pretty => 1}) .Ve
equivalent to:
.Vb 1 $json_text = JSON->new->utf8(1)->pretty(1)->encode($perl_scalar) .Ve
If you want to write a modern perl code which communicates to outer world, you should use \*(C`encode_json\*(C' (supposed that \s-1JSON\s0 data are encoded in \s-1UTF-8\s0).
The opposite of \*(C`to_json\*(C': expects a json string and tries to parse it, returning the resulting reference.
This function call is functionally identical to:
.Vb 1 $perl_scalar = JSON->decode($json_text) .Ve
Takes a hash reference as the second.
.Vb 1 $perl_scalar = from_json($json_text, $flag_hashref) .Ve
So,
.Vb 1 $perl_scalar = from_json($json_text, {utf8 => 1}) .Ve
equivalent to:
.Vb 1 $perl_scalar = JSON->new->utf8(1)->decode($json_text) .Ve
If you want to write a modern perl code which communicates to outer world, you should use \*(C`decode_json\*(C' (supposed that \s-1JSON\s0 data are encoded in \s-1UTF-8\s0).
Returns true if the passed scalar represents either JSON::true or JSON::false, two constants that act like 1 and 0 respectively and are also used to represent \s-1JSON\s0 \*(C`true\*(C' and \*(C`false\*(C' in Perl strings.
See \s-1MAPPING\s0, below, for more information on how \s-1JSON\s0 values are mapped to Perl.
If you know a \s-1JSON\s0 text from an outer world - a network, a file content, and so on, is encoded in \s-1UTF-8\s0, you should use \*(C`decode_json\*(C' or \*(C`JSON\*(C' module object with \*(C`utf8\*(C' enable. And the decoded result will contain \s-1UNICODE\s0 characters.
.Vb 4 # from network my $json = JSON->new->utf8; my $json_text = CGI->new->param( \*(Aqjson_data\*(Aq ); my $perl_scalar = $json->decode( $json_text ); # from file content local $/; open( my $fh, \*(Aq<\*(Aq, \*(Aqjson.data\*(Aq ); $json_text = <$fh>; $perl_scalar = decode_json( $json_text ); .Ve
If an outer data is not encoded in \s-1UTF-8\s0, firstly you should \*(C`decode\*(C' it.
.Vb 5 use Encode; local $/; open( my $fh, \*(Aq<\*(Aq, \*(Aqjson.data\*(Aq ); my $encoding = \*(Aqcp932\*(Aq; my $unicode_json_text = decode( $encoding, <$fh> ); # UNICODE # or you can write the below code. # # open( my $fh, "<:encoding($encoding)", \*(Aqjson.data\*(Aq ); # $unicode_json_text = <$fh>; .Ve
In this case, $unicode_json_text is of course \s-1UNICODE\s0 string. So you cannot use \*(C`decode_json\*(C' nor \*(C`JSON\*(C' module object with \*(C`utf8\*(C' enable. Instead of them, you use \*(C`JSON\*(C' module object with \*(C`utf8\*(C' disable or \*(C`from_json\*(C'.
.Vb 3 $perl_scalar = $json->utf8(0)->decode( $unicode_json_text ); # or $perl_scalar = from_json( $unicode_json_text ); .Ve
Or \*(C`encode \*(Aqutf8\*(Aq\*(C' and \*(C`decode_json\*(C':
.Vb 2 $perl_scalar = decode_json( encode( \*(Aqutf8\*(Aq, $unicode_json_text ) ); # this way is not efficient. .Ve
And now, you want to convert your $perl_scalar into \s-1JSON\s0 data and send it to an outer world - a network or a file content, and so on.
Your data usually contains \s-1UNICODE\s0 strings and you want the converted data to be encoded in \s-1UTF-8\s0, you should use \*(C`encode_json\*(C' or \*(C`JSON\*(C' module object with \*(C`utf8\*(C' enable.
.Vb 3 print encode_json( $perl_scalar ); # to a network? file? or display? # or print $json->utf8->encode( $perl_scalar ); .Ve
If $perl_scalar does not contain \s-1UNICODE\s0 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 \*(C`encode_json\*(C' nor \*(C`JSON\*(C' module object with \*(C`utf8\*(C' enable. Instead of them, you use \*(C`JSON\*(C' module object with \*(C`utf8\*(C' disable or \*(C`to_json\*(C'. Note that the resulted text is a \s-1UNICODE\s0 string but no problem to print it.
.Vb 6 # $perl_scalar contains $encoding encoded string values $unicode_json_text = $json->utf8(0)->encode( $perl_scalar ); # or $unicode_json_text = to_json( $perl_scalar ); # $unicode_json_text consists of characters less than 0x100 print $unicode_json_text; .Ve
Or \*(C`decode $encoding\*(C' all string values and \*(C`encode_json\*(C':
.Vb 3 $perl_scalar->{ foo } = decode( $encoding, $perl_scalar->{ foo } ); # ... do it to each string values, then encode_json $json_text = encode_json( $perl_scalar ); .Ve
This method is a proper way but probably not efficient.
See to Encode, perluniintro.
Returns a new \*(C`JSON\*(C' object inherited from either \s-1JSON::XS\s0 or \s-1JSON::PP\s0 that can be used to de/encode \s-1JSON\s0 strings.
All boolean flags described below are by default disabled.
The mutators for flags all return the \s-1JSON\s0 object again and thus calls can be chained:
.Vb 2 my $json = JSON->new->utf8->space_after->encode({a => [1,2]}) => {"a": [1, 2]} .Ve
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 \euXXXX or a double \euHHHH\euLLLLL escape sequence, as per \s-1RFC4627\s0.
If $enable is false, then the encode method will not escape Unicode characters unless required by the \s-1JSON\s0 syntax or other flags. This results in a faster and more compact format.
This feature depends on the used Perl version and environment.
See to \*(L"\s-1UNICODE\s0 \s-1HANDLING\s0 \s-1ON\s0 \s-1PERLS\s0\*(R" in \s-1JSON::PP\s0 if the backend is \s-1PP\s0.
.Vb 2 JSON->new->ascii(1)->encode([chr 0x10401]) => ["\eud801\eudc01"] .Ve
If $enable is true (or missing), then the encode method will encode the resulting \s-1JSON\s0 text as latin1 (or iso-8859-1), escaping any characters outside the code range 0..255.
If $enable is false, then the encode method will not escape Unicode characters unless required by the \s-1JSON\s0 syntax or other flags.
.Vb 2 JSON->new->latin1->encode (["\ex{89}\ex{abc}"] => ["\ex{89}\e\eu0abc"] # (perl syntax, U+abc escaped, U+89 not) .Ve
If $enable is true (or missing), then the encode method will encode the \s-1JSON\s0 result into \s-1UTF-8\s0, 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 \s-1UTF-16\s0 and \s-1UTF-32\s0 encoding families, as described in \s-1RFC4627\s0.
If $enable is false, then the encode method will return the \s-1JSON\s0 string as a (non-encoded) Unicode string, while decode expects thus a Unicode string. Any decoding or encoding (e.g. to \s-1UTF-8\s0 or \s-1UTF-16\s0) needs to be done yourself, e.g. using the Encode module.
Example, output UTF-16BE-encoded \s-1JSON:\s0
.Vb 2 use Encode; $jsontext = encode "UTF-16BE", JSON::XS->new->encode ($object); .Ve
Example, decode UTF-32LE-encoded \s-1JSON:\s0
.Vb 2 use Encode; $object = JSON::XS->new->decode (decode "UTF-32LE", $jsontext); .Ve
See to \*(L"\s-1UNICODE\s0 \s-1HANDLING\s0 \s-1ON\s0 \s-1PERLS\s0\*(R" in \s-1JSON::PP\s0 if the backend is \s-1PP\s0.
This enables (or disables) all of the \*(C`indent\*(C', \*(C`space_before\*(C' and \f(CW\*(C`space_after\*(C' (and in the future possibly more) flags in one call to generate the most readable (or most compact) form possible.
Equivalent to:
.Vb 1 $json->indent->space_before->space_after .Ve
The indent space length is three and \s-1JSON::XS\s0 cannot change the indent space length.
If $enable is true (or missing), then the \*(C`encode\*(C' method will use a multiline format as output, putting every array member or object/hash key-value pair into its own line, identifying them properly.
If $enable is false, no newlines or indenting will be produced, and the resulting \s-1JSON\s0 text is guaranteed not to contain any \*(C`newlines\*(C'.
This setting has no effect when decoding \s-1JSON\s0 texts.
The indent space length is three. With \s-1JSON::PP\s0, you can also access \*(C`indent_length\*(C' to change indent space length.
If $enable is true (or missing), then the \*(C`encode\*(C' method will add an extra optional space before the \*(C`:\*(C' separating keys from values in \s-1JSON\s0 objects.
If $enable is false, then the \*(C`encode\*(C' method will not add any extra space at those places.
This setting has no effect when decoding \s-1JSON\s0 texts.
Example, space_before enabled, space_after and indent disabled:
.Vb 1 {"key" :"value"} .Ve
If $enable is true (or missing), then the \*(C`encode\*(C' method will add an extra optional space after the \*(C`:\*(C' separating keys from values in \s-1JSON\s0 objects and extra whitespace after the \*(C`,\*(C' separating key-value pairs and array members.
If $enable is false, then the \*(C`encode\*(C' method will not add any extra space at those places.
This setting has no effect when decoding \s-1JSON\s0 texts.
Example, space_before and indent disabled, space_after enabled:
.Vb 1 {"key": "value"} .Ve
If $enable is true (or missing), then \*(C`decode\*(C' will accept some extensions to normal \s-1JSON\s0 syntax (see below). \*(C`encode\*(C' will not be affected in anyway. Be aware that this option makes you accept invalid \s-1JSON\s0 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 \*(C`decode\*(C' will only accept valid \s-1JSON\s0 texts.
Currently accepted extensions are:
If $enable is true (or missing), then the \*(C`encode\*(C' method will output \s-1JSON\s0 objects by sorting their keys. This is adding a comparatively high overhead.
If $enable is false, then the \*(C`encode\*(C' 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 \s-1JSON\s0 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.
This setting has no effect when decoding \s-1JSON\s0 texts.
If $enable is true (or missing), then the \*(C`encode\*(C' method can convert a non-reference into its corresponding string, number or null \s-1JSON\s0 value, which is an extension to \s-1RFC4627\s0. Likewise, \*(C`decode\*(C' will accept those \s-1JSON\s0 values instead of croaking.
If $enable is false, then the \*(C`encode\*(C' method will croak if it isn't passed an arrayref or hashref, as \s-1JSON\s0 texts must either be an object or array. Likewise, \*(C`decode\*(C' will croak if given something that is not a \s-1JSON\s0 object or array.
.Vb 2 JSON->new->allow_nonref->encode ("Hello, World!") => "Hello, World!" .Ve
If $enable is true (or missing), then \*(L"encode\*(R" will *not* throw an exception when it encounters values it cannot represent in \s-1JSON\s0 (for example, filehandles) but instead will encode a \s-1JSON\s0 \*(L"null\*(R" value. Note that blessed objects are not included here and are handled separately by c<allow_nonref>.
If $enable is false (the default), then \*(L"encode\*(R" will throw an exception when it encounters anything it cannot encode as \s-1JSON\s0.
This option does not affect \*(L"decode\*(R" 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 \*(C`encode\*(C' method will not barf when it encounters a blessed reference. Instead, the value of the \fBconvert_blessed option will decide whether \*(C`null\*(C' (\*(C`convert_blessed\*(C' disabled or no \*(C`TO_JSON\*(C' method found) or a representation of the object (\*(C`convert_blessed\*(C' enabled and \*(C`TO_JSON\*(C' method found) is being encoded. Has no effect on \*(C`decode\*(C'.
If $enable is false (the default), then \*(C`encode\*(C' will throw an exception when it encounters a blessed object.
If $enable is true (or missing), then \*(C`encode\*(C', upon encountering a blessed object, will check for the availability of the \*(C`TO_JSON\*(C' 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 \f(CW\*(C`TO_JSON\*(C' method is found, the value of \*(C`allow_blessed\*(C' will decide what to do.
The \*(C`TO_JSON\*(C' method may safely call die if it wants. If \*(C`TO_JSON\*(C' returns other blessed objects, those will be handled in the same way. \*(C`TO_JSON\*(C' must take care of not causing an endless recursion cycle (== crash) in this case. The name of \*(C`TO_JSON\*(C' 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 \*(C`to_json\*(C' function or method.
This setting does not yet influence \*(C`decode\*(C' in any way.
If $enable is false, then the \*(C`allow_blessed\*(C' setting will decide what to do when a blessed object is found.
When $coderef is specified, it will be called from \*(C`decode\*(C' each time it decodes a \s-1JSON\s0 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 (\s-1NOTE:\s0 not \*(C`undef\*(C', 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 \*(C`decode\*(C' will not change the deserialised hash in any way.
Example, convert all \s-1JSON\s0 objects into the integer 5:
.Vb 6 my $js = JSON->new->filter_json_object (sub { 5 }); # returns [5] $js->decode (\*(Aq[{}]\*(Aq); # the given subroutine takes a hash reference. # throw an exception because allow_nonref is not enabled # so a lone 5 is not allowed. $js->decode (\*(Aq{"a":1, "b":2}\*(Aq); .Ve
Works remotely similar to \*(C`filter_json_object\*(C', but is only called for \s-1JSON\s0 objects having a single key named $key.
This $coderef is called before the one specified via \f(CW\*(C`filter_json_object\*(C', if any. It gets passed the single value in the \s-1JSON\s0 object. If it returns a single value, it will be inserted into the data structure. If it returns nothing (not even \*(C`undef\*(C' but the empty list), the callback from \*(C`filter_json_object\*(C' 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 \*(C`filter_json_object\*(C' 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 \s-1JSON\s0 objects are as close to the type-tagged value concept as \s-1JSON\s0 gets (it's basically an \s-1ID/VALUE\s0 tuple). Of course, \s-1JSON\s0 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 \*(C`_\|_class_whatever_\|_\*(C', or \f(CW\*(C`$_\|_dollars_are_rarely_used_\|_$\*(C' or \*(C`}ugly_brace_placement\*(C', or even things like \*(C`_\|_class_md5sum(classname)_\|_\*(C', to reduce the risk of clashing with real hashes.
Example, decode \s-1JSON\s0 objects of the form \*(C`{ "_\|_widget_\|_" => <id> }\*(C' into the corresponding $WIDGET{<id>} object:
.Vb 7 # return whatever is in $WIDGET{5}: JSON ->new ->filter_json_single_key_object (_\|_widget_\|_ => sub { $WIDGET{ $_[0] } }) ->decode (\*(Aq{"_\|_widget_\|_": 5\*(Aq) \& # this can be used with a TO_JSON method in some "widget" class # for serialisation to json: sub WidgetBase::TO_JSON { my ($self) = @_; \& unless ($self->{id}) { $self->{id} = ..get..some..id..; $WIDGET{$self->{id}} = $self; } \& { _\|_widget_\|_ => $self->{id} } } .Ve
With \s-1JSON::XS\s0, this flag resizes strings generated by either \f(CW\*(C`encode\*(C' or \*(C`decode\*(C' to their minimum size possible. This can save memory when your \s-1JSON\s0 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 \s-1JSON::PP\s0, it is noop about resizing strings but tries \f(CW\*(C`utf8::downgrade\*(C' to the returned string by \*(C`encode\*(C'. See to utf8.
See to \*(L"OBJECT-ORIENTED \s-1INTERFACE\s0\*(R" in \s-1JSON::XS\s0 and \*(L"\s-1METHODS\s0\*(R" in \s-1JSON::PP\s0.
Sets the maximum nesting level (default 512) accepted while encoding or decoding. If a higher nesting level is detected in \s-1JSON\s0 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`{\*(C' or \*(C`[\*(C' 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. (\s-1JSON::XS\s0)
With \s-1JSON::PP\s0 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.
See \*(L"\s-1SECURITY\s0 \s-1CONSIDERATIONS\s0\*(R" in \s-1JSON::XS\s0 for more info on why this is useful.
Set the maximum length a \s-1JSON\s0 text may have (in bytes) where decoding is being attempted. The default is 0, meaning no limit. When \*(C`decode\*(C' 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`encode\*(C' (yet).
If no argument is given, the limit check will be deactivated (same as when \f(CW0 is specified).
See \*(L"\s-1SECURITY\s0 \s-1CONSIDERATIONS\s0\*(R" in \s-1JSON::XS\s0, below, for more info on why this is useful.
Converts the given Perl data structure (a simple scalar or a reference to a hash or array) to its \s-1JSON\s0 representation. Simple scalars will be converted into \s-1JSON\s0 string or number sequences, while references to arrays become \s-1JSON\s0 arrays and references to hashes become \s-1JSON\s0 objects. Undefined Perl values (e.g. \*(C`undef\*(C') become \s-1JSON\s0 \*(C`null\*(C' values. References to the integers 0 and 1 are converted into \*(C`true\*(C' and \*(C`false\*(C'.
The opposite of \*(C`encode\*(C': expects a \s-1JSON\s0 text and tries to parse it, returning the resulting simple scalar or reference. Croaks on error.
\s-1JSON\s0 numbers and strings become simple Perl scalars. \s-1JSON\s0 arrays become Perl arrayrefs and \s-1JSON\s0 objects become Perl hashrefs. \*(C`true\*(C' becomes \f(CW1 (\*(C`JSON::true\*(C'), \*(C`false\*(C' becomes 0 (\*(C`JSON::false\*(C') and \f(CW\*(C`null\*(C' becomes \*(C`undef\*(C'.
This works like the \*(C`decode\*(C' method, but instead of raising an exception when there is trailing garbage after the first \s-1JSON\s0 object, it will silently stop parsing there and return the number of characters consumed so far.
.Vb 2 JSON->new->decode_prefix ("[1] the tail") => ([], 3) .Ve
See to \*(L"OBJECT-ORIENTED \s-1INTERFACE\s0\*(R" in \s-1JSON::XS\s0
Returns a boolean value about above some properties.
The available properties are \*(C`ascii\*(C', \*(C`latin1\*(C', \*(C`utf8\*(C', \f(CW\*(C`indent\*(C',\*(C`space_before\*(C', \*(C`space_after\*(C', \*(C`relaxed\*(C', \*(C`canonical\*(C', \f(CW\*(C`allow_nonref\*(C', \*(C`allow_unknown\*(C', \*(C`allow_blessed\*(C', \*(C`convert_blessed\*(C', \f(CW\*(C`shrink\*(C', \*(C`max_depth\*(C' and \*(C`max_size\*(C'.
.Vb 5 $boolean = $json->property(\*(Aqutf8\*(Aq); => 0 $json->utf8; $boolean = $json->property(\*(Aqutf8\*(Aq); => 1 .Ve
Sets the property with a given boolean value.
.Vb 1 $json = $json->property($property_name => $boolean); .Ve
With no argument, it returns all the above properties as a hash reference.
.Vb 1 $flag_hashref = $json->property(); .Ve
In some cases, there is the need for incremental parsing of \s-1JSON\s0 texts. This module does allow you to parse a \s-1JSON\s0 stream incrementally. It does so by accumulating text until it has a full \s-1JSON\s0 object, which it then can decode. This process is similar to using \*(C`decode_prefix\*(C' to see if a full \s-1JSON\s0 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 \s-1JSON\s0 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 \s-1JSON\s0 text has been seen. This means you need to set resource limits (e.g. \*(C`max_size\*(C') to ensure the parser will stop parsing in the presence if syntax errors.
The following methods implement this incremental parser.
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 \s-1JSON\s0 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 \s-1JSON\s0 object. If that is successful, it will return this object, otherwise it will return \*(C`undef\*(C'. If there is a parse error, this method will croak just as \*(C`decode\*(C' would do (one can then use \f(CW\*(C`incr_skip\*(C' 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 \s-1JSON\s0 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 \s-1JSON\s0 texts will be lost.
Example: Parse some \s-1JSON\s0 arrays/objects in a given string and return them.
.Vb 1 my @objs = JSON->new->incr_parse ("[5][7][1,2]"); .Ve
This method returns the currently stored \s-1JSON\s0 fragment as an lvalue, that is, you can manipulate it. This only works when a preceding call to \f(CW\*(C`incr_parse\*(C' 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 \s-1JSON\s0 object or b) parsing multiple \s-1JSON\s0 objects separated by non-JSON text (such as commas).
.Vb 1 $json->incr_text =~ s/\es*,\es*//; .Ve
In Perl 5.005, \*(C`lvalue\*(C' attribute is not available. You must write codes like the below:
.Vb 3 $string = $json->incr_text; $string =~ s/\es*,\es*//; $json->incr_text( $string ); .Ve
This will reset the state of the incremental parser and will remove the parsed text from the input buffer. This is useful after \*(C`incr_parse\*(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.
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 \s-1JSON\s0 objects and want to ignore any trailing data, which means you have to reset the parser after each successful decode.
See to \*(L"\s-1INCREMENTAL\s0 \s-1PARSING\s0\*(R" in \s-1JSON::XS\s0 for examples.
If you use \*(C`JSON\*(C' with additional \*(C`-support_by_pp\*(C', some methods are available even with \s-1JSON::XS\s0. See to \*(L"\s-1USE\s0 \s-1PP\s0 \s-1FEATURES\s0 \s-1EVEN\s0 \s-1THOUGH\s0 \s-1XS\s0 \s-1BACKEND\s0\*(R".
.Vb 1 BEING { $ENV{PERL_JSON_BACKEND} = \*(AqJSON::XS\*(Aq } use JSON -support_by_pp; my $json = JSON->new; $json->allow_nonref->escape_slash->encode("/"); \& # functional interfaces too. print to_json(["/"], {escape_slash => 1}); print from_json(\*(Aq["foo"]\*(Aq, {utf8 => 1}); .Ve
If you do not want to all functions but \*(C`-support_by_pp\*(C', use \*(C`-no_export\*(C'.
.Vb 2 use JSON -support_by_pp, -no_export; # functional interfaces are not exported. .Ve
If $enable is true (or missing), then \*(C`decode\*(C' will accept any \s-1JSON\s0 strings quoted by single quotations that are invalid \s-1JSON\s0 format.
.Vb 3 $json->allow_singlequote->decode({"foo":\*(Aqbar\*(Aq}); $json->allow_singlequote->decode({\*(Aqfoo\*(Aq:"bar"}); $json->allow_singlequote->decode({\*(Aqfoo\*(Aq:\*(Aqbar\*(Aq}); .Ve
As same as the \*(C`relaxed\*(C' option, this option may be used to parse application-specific files written by humans.
If $enable is true (or missing), then \*(C`decode\*(C' will accept bare keys of \s-1JSON\s0 object that are invalid \s-1JSON\s0 format.
As same as the \*(C`relaxed\*(C' option, this option may be used to parse application-specific files written by humans.
.Vb 1 $json->allow_barekey->decode(\*(Aq{foo:"bar"}\*(Aq); .Ve
If $enable is true (or missing), then \*(C`decode\*(C' will convert the big integer Perl cannot handle as integer into a Math::BigInt object and convert a floating number (any) into a Math::BigFloat.
On the contrary, \*(C`encode\*(C' converts \*(C`Math::BigInt\*(C' objects and \*(C`Math::BigFloat\*(C' objects into \s-1JSON\s0 numbers with \*(C`allow_blessed\*(C' enable.
.Vb 4 $json->allow_nonref->allow_blessed->allow_bignum; $bigfloat = $json->decode(\*(Aq2.000000000000000000000000001\*(Aq); print $json->encode($bigfloat); # => 2.000000000000000000000000001 .Ve
See to \s-1MAPPING\s0 about the conversion of \s-1JSON\s0 number.
The unescaped [\ex00-\ex1f\ex22\ex2f\ex5c] strings are invalid in \s-1JSON\s0 strings and the module doesn't allow to \*(C`decode\*(C' to these (except for \ex2f). If $enable is true (or missing), then \*(C`decode\*(C' will accept these unescaped strings.
.Vb 2 $json->loose->decode(qq|["abc def"]|); .Ve
See to \*(L"\s-1JSON::PP\s0 \s-1OWN\s0 \s-1METHODS\s0\*(R" in \s-1JSON::PP\s0.
According to \s-1JSON\s0 Grammar, slash (U+002F) is escaped. But by default \s-1JSON\s0 backend modules encode strings without escaping slash.
If $enable is true (or missing), then \*(C`encode\*(C' will escape slashes.
With \s-1JSON::XS\s0, The indent space length is 3 and cannot be changed. With \s-1JSON::PP\s0, it sets the indent space length with the given $length. The default is 3. The acceptable range is 0 to 15.
If $function_name or $subroutine_ref are set, its sort routine are used.
.Vb 2 $js = $pc->sort_by(sub { $JSON::PP::a cmp $JSON::PP::b })->encode($obj); # is($js, q|{"a":1,"b":2,"c":3,"d":4,"e":5,"f":6,"g":7,"h":8,"i":9}|); \& $js = $pc->sort_by(\*(Aqown_sort\*(Aq)->encode($obj); # is($js, q|{"a":1,"b":2,"c":3,"d":4,"e":5,"f":6,"g":7,"h":8,"i":9}|); \& sub JSON::PP::own_sort { $JSON::PP::a cmp $JSON::PP::b } .Ve
As the sorting routine runs in the \s-1JSON::PP\s0 scope, the given subroutine name and the special variables $a, $b will begin with '\s-1JSON::PP::\s0'.
If $integer is set, then the effect is same as \*(C`canonical\*(C' on.
See to \*(L"\s-1JSON::PP\s0 \s-1OWN\s0 \s-1METHODS\s0\*(R" in \s-1JSON::PP\s0.
See to \*(L"\s-1MAPPING\s0\*(R" in \s-1JSON::XS\s0.
The \*(C`JSON\*(C' constructor method returns an object inherited from the backend module, and \s-1JSON::XS\s0 object is a blessed scalar reference while \s-1JSON::PP\s0 is a blessed hash reference.
So, your program should not depend on the backend module, especially returned objects should not be modified.
.Vb 2 my $json = JSON->new; # XS or PP? $json->{stash} = \*(Aqthis is xs object\*(Aq; # this code may raise an error! .Ve
To check the backend module, there are some methods - \*(C`backend\*(C', \*(C`is_pp\*(C' and \*(C`is_xs\*(C'.
.Vb 1 JSON->backend; # \*(AqJSON::XS\*(Aq or \*(AqJSON::PP\*(Aq JSON->backend->is_pp: # 0 or 1 JSON->backend->is_xs: # 1 or 0 $json->is_xs; # 1 or 0 $json->is_pp; # 0 or 1 .Ve
If you set an environment variable \*(C`PERL_JSON_BACKEND\*(C', the calling action will be changed.
These ideas come from DBI::PurePerl mechanism.
example:
.Vb 2 BEGIN { $ENV{PERL_JSON_BACKEND} = \*(AqJSON::PP\*(Aq } use JSON; # always uses JSON::PP .Ve
In future, it may be able to specify another module.
But If you \*(C`use\*(C' \*(C`JSON\*(C' passing the optional string \*(C`-support_by_pp\*(C', it makes a part of those unsupported methods available. This feature is achieved by using \s-1JSON::PP\s0 in \*(C`de/encode\*(C'.
.Vb 4 BEGIN { $ENV{PERL_JSON_BACKEND} = 2 } # with JSON::XS use JSON -support_by_pp; my $json = JSON->new; $json->allow_nonref->escape_slash->encode("/"); .Ve
At this time, the returned object is a \*(C`JSON::Backend::XS::Supportable\*(C' object (re-blessed \s-1XS\s0 object), and by checking \s-1JSON::XS\s0 unsupported flags in de/encoding, can support some unsupported methods - \*(C`loose\*(C', \*(C`allow_bignum\*(C', \f(CW\*(C`allow_barekey\*(C', \*(C`allow_singlequote\*(C', \*(C`escape_slash\*(C' and \*(C`indent_length\*(C'.
When any unsupported methods are not enable, \*(C`XS de/encode\*(C' will be used as is. The switch is achieved by changing the symbolic tables.
\f(CW\*(C`-support_by_pp\*(C' is effective only when the backend module is \s-1JSON::XS\s0 and it makes the de/encoding speed down a bit.
See to \*(L"\s-1JSON::PP\s0 \s-1SUPPORT\s0 \s-1METHODS\s0\*(R".
See to \*(L"Transition ways from 1.xx to 2.xx.\*(R"
.Vb 1 use JSON -support_by_pp; .Ve
\s-1JSON::XS\s0, \s-1JSON::PP\s0
\f(CW\*(C`RFC4627\*(C'(<http://www.ietf.org/rfc/rfc4627.txt>)
\s-1JSON::XS\s0 was written by Marc Lehmann <schmorp[at]schmorp.de>
The release of this new version owes to the courtesy of Marc Lehmann.
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.