JSON::PP(3perl)

πŸ’– JSON::PP β€” the JSON::PP(3perl) era πŸ’–

ok so bestie. put your phone down for one sec because we're about to talk about JSON::PP, a JSON::XS compatible pure-Perl module. yes she's pure-Perl. yes she's iconic. let's go πŸ’…


✨ NAME ✨

JSON::PP β€” literally a JSON::XS compatible pure-Perl module. that's the whole vibe. no C compiler required, she does it all herself 🫢


✨ SYNOPSIS ✨

ok so here's how you pull up on her:

use JSON::PP;

# exported functions, they croak on error
# and expect/generate UTF-8

$utf8_encoded_json_text = encode_json $perl_hash_or_arrayref;
$perl_hash_or_arrayref  = decode_json $utf8_encoded_json_text;

# OO-interface

$json = JSON::PP->new->ascii->pretty->allow_nonref;

$pretty_printed_json_text = $json->encode( $perl_scalar );
$perl_scalar = $json->decode( $json_text );

# Note that JSON version 2.0 and above will automatically use
# JSON::XS or JSON::PP, so you should be able to just:

use JSON;

not the use JSON; at the bottom being the lazy girl hack 😭 JSON version 2.0 and up will automatically pick JSON::XS or JSON::PP for you, so honestly you can just do that and let her handle it.


✨ DESCRIPTION ✨

JSON::PP is a pure perl JSON decoder/encoder, and she's (almost) compatible with the much faster JSON::XS β€” that one's written by Marc Lehmann in C. when you use JSON without having installed JSON::XS, JSON::PP is the fallback module that shows up for you. she's the understudy who ate πŸ’…

because of this fallback thing that JSON.pm does, JSON::PP tries not to be more JavaScript-friendly than JSON::XS β€” like, she's not out here escaping extra characters such as U+2028 and U+2029, etc. the whole point is that you don't silently lose that JavaScript-friendliness when you use JSON.pm and then install JSON::XS for speed, or by accident πŸ™ˆ

so if what you actually need is a JavaScript-friendly, RFC7159-compliant pure perl module, try JSON::Tiny β€” she's derived from the Mojolicious web framework and is also smaller and faster than JSON::PP 🌸

JSON::PP has been in the Perl core since Perl 5.14, mainly for CPAN toolchain modules to parse META.json. she's literally built in, bestie. she was always there for you πŸ₯Ή


✨ FUNCTIONAL INTERFACE ✨

lowkey important: this section is taken from JSON::XS almost verbatim. and heads up, encode_json and decode_json are exported by default πŸŽ€

🌟 encode_json

$json_text = encode_json $perl_scalar

converts the Perl data structure you hand her into a UTF-8 encoded, binary string β€” meaning the string contains octets only. and if something goes wrong? she croaks on error. no silent failing, she will let you know 😭

this function call is functionally identical to:

$json_text = JSON::PP->new->utf8->encode($perl_scalar)

...except being faster. periodt. ⚑

🌟 decode_json

$perl_scalar = decode_json $json_text

the opposite of encode_json: she expects a UTF-8 (binary) string and tries to parse that as an UTF-8 encoded JSON text, returning the resulting reference. croaks on error, same energy πŸ’€

this function call is functionally identical to:

$perl_scalar = JSON::PP->new->utf8->decode($json_text)

...except being faster. again. she said efficiency 🫢

🌟 JSON::PP::is_bool

$is_boolean = JSON::PP::is_bool($scalar)

returns true if the scalar you passed represents either JSON::PP::true or JSON::PP::false β€” two constants that act like 1 and 0 respectively, and are also used to represent JSON "true" and "false" in Perl strings ✨

and on perl 5.36 and above, she'll also return true when you give her one of perl's standard boolean values, like the result of a comparison. glow up fr fr πŸ‘‘

see MAPPING below for the info on how JSON values map to Perl.


✨ OBJECT-ORIENTED INTERFACE ✨

this section is also taken from JSON::XS, bestie. consistency queen.

the object oriented interface lets you configure your own encoding or decoding style, within the limits of supported formats. your JSON, your rules πŸ’…

🌟 new

$json = JSON::PP->new

creates a new JSON::PP object that can be used to de/encode JSON strings. all the boolean flags described below are by default disabled β€” with the exception of allow_nonref, which defaults to enabled since version 4.0 πŸŽ€

and the best part? the mutators for flags all return the JSON::PP object again, so you can chain calls like a little necklace:

my $json = JSON::PP->new->utf8->space_after->encode({a => [1,2]})
=> {"a": [1, 2]}

look at that glow ✨

🌟 ascii

$json = $json->ascii([$enable])

$enabled = $json->get_ascii

if $enable is true (or missing), then the encode method will not generate characters outside the code range 0..127 (which is ASCII). any Unicode characters outside that range get escaped using either a single \uXXXX (BMP characters) or a double \uHHHH\uLLLLL escape sequence, 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. flexible icon πŸ’œ

if $enable is false, then the encode method will not escape Unicode characters unless required by the JSON syntax or other flags. that means a faster and more compact format ⚑

see also the section ENCODING/CODESET FLAG NOTES later in this document.

the main use for this flag is to produce JSON texts that can be transmitted over a 7-bit channel, because the encoded JSON texts will not contain any 8 bit characters.

JSON::PP->new->ascii(1)->encode([chr 0x10401])
=> ["\ud801\udc01"]

🌟 latin1

$json = $json->latin1([$enable])

$enabled = $json->get_latin1

if $enable is true (or missing), then the encode method will encode the resulting JSON text as latin1 (or iso-8859-1), escaping any characters outside the code range 0..255. the resulting string can be treated as a latin1-encoded JSON text or a native Unicode string. the decode method will not be affected in any way by this flag, because decode by default expects Unicode, which is a strict superset of latin1 πŸ¦‹

if $enable is false, then the encode method will not escape Unicode characters unless required by the JSON syntax or other flags.

see also the section ENCODING/CODESET FLAG NOTES later in this document.

the main use for this flag is efficiently encoding binary data as JSON text, since most octets will not be escaped, which gives you 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 transferring) β€” a rare encoding for JSON 😬 so it's most useful when you want to store data structures known to contain binary data efficiently in files or databases, not when you're talking to other JSON encoders/decoders.

JSON::PP->new->latin1->encode (["\x{89}\x{abc}"]
=> ["\x{89}\\u0abc"]    # (perl syntax, U+abc escaped, U+89 not)

🌟 utf8

$json = $json->utf8([$enable])

$enabled = $json->get_utf8

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, so they're 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. might. no promises, she said maybe πŸ‘€

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. so any decoding or encoding (e.g. to UTF-8 or UTF-16) needs to be done yourself, e.g. using the Encode module.

see also the section ENCODING/CODESET FLAG NOTES later in this document.

example, output UTF-16BE-encoded JSON:

use Encode;
$jsontext = encode "UTF-16BE", JSON::PP->new->encode ($object);

example, decode UTF-32LE-encoded JSON:

use Encode;
$object = JSON::PP->new->decode (decode "UTF-32LE", $jsontext);

🌟 pretty

$json = $json->pretty([$enable])

this enables (or disables) all of the indent, space_before and space_after (and in the future possibly more) flags in one call to generate the most readable (or most compact) form possible. one button, maximum slay πŸ’…βœ¨

🌟 indent

$json = $json->indent([$enable])

$enabled = $json->get_indent

if $enable is true (or missing), then the encode method will use a multiline format as output, putting every array member or object/hash key-value pair into its own line, indenting them properly. aesthetic 😌

if $enable is false, no newlines or indenting will be produced, and the resulting JSON text is guaranteed not to contain any "newlines". clean. compact. minimal.

this setting has no effect when decoding JSON texts.

the default indent space length is three. you can use indent_length to change the length πŸŽ€

🌟 space_before

$json = $json->space_before([$enable])

$enabled = $json->get_space_before

if $enable is true (or missing), then the encode method will add an extra optional space before the ":" separating keys from values in JSON objects.

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

this setting has no effect when decoding JSON texts. and you will also most likely combine this setting with space_after β€” they're a duo fr fr 🫢

example, space_before enabled, space_after and indent disabled:

{"key" :"value"}

🌟 space_after

$json = $json->space_after([$enable])

$enabled = $json->get_space_after

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.

this setting has no effect when decoding JSON texts.

example, space_before and indent disabled, space_after enabled:

{"key": "value"}

🌟 relaxed

$json = $json->relaxed([$enable])

$enabled = $json->get_relaxed

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.

🚨 bestie, listen to me. be aware that this option makes you accept invalid JSON texts as if they were valid! she said chaos mode. the original author suggests only using 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:

[
   1,
   2, <- this comma not normally allowed
]
{
   "k1": "v1",
   "k2": "v2", <- this comma not normally allowed
}
  • shell-style '#'-comments πŸ’¬

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.

[
   1, # this comment not allowed in JSON
      # neither this one...
]
  • C-style multiple-line '/* */'-comments (JSON::PP only) 🌈

whenever JSON allows whitespace, C-style multiple-line comments are additionally allowed. everything between /* and */ is a comment, after which more white-space and comments are allowed.


ok that's part 1 bestie, hold on, there's more coming πŸ’–

and ooh, the comment sitch πŸ’¬ if comments are on the menu, the /* ... */ energy looks like this:

 [
    1, /* this comment not allowed in JSON */
       /* neither this one... */
 ]
  • C++-style one-line //-comments (JSON::PP only πŸ¦‹) β€” anywhere JSON says "whitespace goes here", you can ALSO drop a // one-liner. it dies at the first carriage-return or line-feed character, and after that you can have more whitespace and more comments, like a lil comment conga line πŸ’ƒ
 [
    1, // this comment not allowed in JSON
       // neither this one...
 ]
  • literal ASCII TAB characters in strings β€” yes bestie, actual raw TABs are allowed inside strings now, and they get treated exactly like "\t" πŸŽ€
 [
    "Hello\tWorld",
    "Hello<TAB>World", # literal <TAB> would not normally be allowed
 ]

πŸ’… canonical πŸ’…

$json = $json->canonical([$enable])

$enabled = $json->get_canonical

if $enable is true (or you just don't pass anything), then encode sorts the keys of your JSON objects when it spits them out. lowkey that costs you, because it adds a comparatively high overhead πŸ’€

if $enable is false, encode just dumps key-value pairs in whatever order Perl happens to store them in β€” which will probably be different between runs of the same script, and from 5.18 onwards it can literally change within the same run. chaos, honestly 😭

this option is your girl if you want one data structure to always encode into the same JSON text (given the same overall settings). if it's off, the same hash might encode differently even though it holds the same data, because key-value pairs have no inherent ordering in Perl. that's just how it is ✨

this setting does nothing when you're decoding JSON texts.
also, currently, it has no effect on tied hashes. just saying πŸ‘€

🌸 allow_nonref 🌸

$json = $json->allow_nonref([$enable])

$enabled = $json->get_allow_nonref

plot twist: unlike basically every other boolean option here, this one is enabled by default starting with version 4.0 πŸ‘‘

if $enable is true (or missing), encode can turn a non-reference into its matching string, number or null JSON value β€” and that's an extension to RFC4627, so congrats, you're off the spec. likewise, decode will happily accept those JSON values instead of croaking 🫢

if $enable is false, encode will croak if you didn't hand it an arrayref or hashref, because JSON texts hafta be an object or an array. same energy on decode β€” hand it something that ain't a JSON object or array and it croaks 😀

example, encoding a Perl scalar as a JSON value with allow_nonref OFF, which ends in an error:

JSON::PP->new->allow_nonref(0)->encode ("Hello, World!")
=> hash- or arrayref expected...

✨ allow_unknown ✨

$json = $json->allow_unknown([$enable])

$enabled = $json->get_allow_unknown

if $enable is true (or missing), encode won't throw an exception when it bumps into values it can't represent in JSON (filehandles, for example) β€” instead it encodes a JSON null value. but careful bestie: blessed objects are not included in this, they get handled separately by allow_blessed πŸ’…

if $enable is false (that's the default), encode throws an exception the second it meets anything it can't encode as JSON.

this option does not touch decode in any way, and the recommendation is to leave it off unless you actually know your communications partner πŸ‘€

πŸ¦‹ allow_blessed πŸ¦‹

$json = $json->allow_blessed([$enable])

$enabled = $json->get_allow_blessed

peep OBJECT SERIALISATION for the details, bestie.

if $enable is true (or missing), encode will not barf when it encounters a blessed reference it can't otherwise convert. instead, a JSON null value gets encoded in place of the object. iconic, honestly.

if $enable is false (the default), encode throws an exception when it encounters a blessed object it can't convert otherwise.

this setting has zero effect on decode.

πŸŽ€ convert_blessed πŸŽ€

$json = $json->convert_blessed([$enable])

$enabled = $json->get_convert_blessed

again, OBJECT SERIALISATION has the full tea β˜•

if $enable is true (or missing), then encode, upon encountering a blessed object, checks whether a TO_JSON method is available on the object's class. if it finds one, it calls it in scalar context and encodes the resulting scalar instead of the object. slay πŸ’…

the TO_JSON method may safely call die if it wants to. and if TO_JSON returns other blessed objects, those get handled the exact same way. TO_JSON must take care not to cause an endless recursion cycle (== crash πŸ’€) in this case. the name 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 because it avoids collisions with any to_json function or method. iykyk.

if $enable is false (the default), encode will not consider this type of conversion at all.

this setting has zero effect on decode.

🌈 allow_tags 🌈

$json = $json->allow_tags([$enable])

$enabled = $json->get_allow_tags

OBJECT SERIALISATION, once again, has the details.

if $enable is true (or missing), then encode, upon encountering a blessed object, checks whether a FREEZE method is available on the object's class. if it is, that method gets used to serialise the object into a nonstandard tagged JSON value (which, no cap, JSON decoders cannot decode 😭).

it also makes decode parse those tagged JSON values and deserialise them by calling the THAW method.

if $enable is false (the default), encode won't consider this type of conversion, and tagged JSON values will cause a parse error in decode β€” exactly as if tags were never part of the grammar. rude but fair βœ‹

πŸ“ boolean_values πŸ“

$json->boolean_values([$false, $true])

($false,  $true) = $json->get_boolean_values

by default, JSON booleans get decoded as overloaded $JSON::PP::false and $JSON::PP::true objects.

with this method you can bring your own boolean values for decoding β€” on decode, JSON false gets decoded as a copy of $false, and JSON true gets decoded as $true. ("copy" here means the same thing as assigning a value to another variable, i.e. $copy = $false.)

this is lowkey perfect when you wanna pass a decoded data structure straight into other serialisers like YAML, Data::MessagePack and so on 🫢

note that this only works when you decode. you can totally set incompatible boolean objects (like boolean), but when you encode a data structure holding those boolean objects, you still need to enable convert_blessed β€” and add a TO_JSON method if necessary. no shortcuts, bestie.

calling this method with no arguments at all resets the booleans back to their default values.

and get_boolean_values returns both the $false and $true values, or the empty list when they're set to the default ✨

πŸ‘‘ core_bools πŸ‘‘

$json->core_bools([$enable]);

if $enable is true (or missing), then decode will produce standard perl boolean values. equivalent to calling:

$json->boolean_values(!!1, !!0)

get_core_bools returns true if this has been set. on perl 5.36, it'll also return true if the boolean values have been set to perl's core booleans using the boolean_values method πŸ’…

the methods unblessed_bool and get_unblessed_bool are provided as aliases, for compatibility with Cpanel::JSON::XS. teamwork, fr fr 🫢

🧚 filter_json_object 🧚

$json = $json->filter_json_object([$coderef])

when $coderef is specified, it gets called from decode every single time a JSON object is decoded. the only argument is a reference to the newly-created hash. if the code reference returns a single scalar (it doesn't have to be a reference), that value (or rather a copy of it) gets inserted into the deserialised data structure. if it returns an empty list (NOTE: not undef, because undef is a valid scalar), then the original deserialised hash gets inserted instead. heads up: this setting can slow down decoding considerably 🐌

when $coderef is omitted or undefined, any existing callback is removed and decode won't change the deserialised hash in any way.

example, turning every JSON object into the integer 5:

my $js = JSON::PP->new->filter_json_object(sub { 5 });
# returns [5]
$js->decode('[{}]');
# returns 5
$js->decode('{"a":1, "b":2}');

πŸ’œ filter_json_single_key_object πŸ’œ

$json = $json->filter_json_single_key_object($key [=> $coderef])

works remotely similar to filter_json_object, except it only fires for JSON objects that have a single key named $key πŸ‘€

this $coderef gets called before the one you specified via filter_json_object, if there is one. it gets passed the single value inside the JSON object. if it returns a single value, that value gets inserted into the data structure. if it returns nothing at all (not even undef, just the empty list), then the callback from filter_json_object gets called next, as if no single-key callback had ever been specified.

if $coderef is omitted or undefined, the corresponding callback is disabled. and there can only ever be one callback for a given key. that's the rule πŸ“

since this callback gets called less often than the filter_json_object one, decoding speed usually won't suffer as much. so single-key objects make excellent targets for serialising Perl objects into β€” especially because single-key JSON objects are about as close as JSON ever gets to the type-tagged value concept (it's basically an ID/VALUE tuple). of course, JSON doesn't support this in any way whatsoever, so you need to make sure your data never accidentally looks like a serialised Perl hash 😬

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

example, decoding JSON objects shaped like { "__widget__" => <id> } into the corresponding $WIDGET{<id>} object:

# return whatever is in $WIDGET{5}:
JSON::PP
   ->new
   ->filter_json_single_key_object (__widget__ => sub {
         $WIDGET{ $_[0] }
      })
   ->decode ('{"__widget__": 5')

# 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} }
}

🌟 shrink 🌟

$json = $json->shrink([$enable])

$enabled = $json->get_shrink

if $enable is true (or missing), the string returned by encode will be shrunk β€” i.e. downgraded if possible ✨

the actual definition of what shrink does might change in future versions, but bestie, it will always try to save space at the expense of time. that's the deal.

if $enable is false, then JSON::PP does nothing. vibes only, no shrinking.

🌈 max_depth 🌈

$json = $json->max_depth([$maximum_nesting_depth])

$max_depth = $json->get_max_depth

okay so real talk: this one sets the max nesting level (default 512) that's accepted while encoding or decoding. πŸ’… If a bigger nesting level shows up in your JSON text or your Perl data structure, the encoder and decoder just stop and croak right at that point. no warning, no mercy, it's giving "we said what we said".

And how do we even count "nesting level" bestie? Two ways, lowkey:

  • the number of hash- or arrayrefs the encoder has to traverse to reach a given point, or
  • the number of { or [ characters you've crossed (without their matching closing parenthesis) to reach a given character in a string. πŸ¦‹

Setting the max depth to one disallows any nesting, so that's how you make sure the object is only a single hash/object or a single array. simple. iconic. πŸ’–

If you give no argument at all, the highest possible setting gets used, which is... rarely useful. ngl it's giving "why would you". πŸ™ˆ

See "SECURITY CONSIDERATIONS" in JSON::XS for more info on why this is useful. πŸ”₯

πŸ’Ύ max_size

$json = $json->max_size([$maximum_string_size])

$max_size = $json->get_max_size

Sets the max length a JSON text may have (in bytes) wherever decoding is being attempted. Default is 0, meaning like... no limit, go off. πŸŽ€

When "decode" gets called on a string that's longer than this many bytes, it will not attempt to decode the string, it'll just throw an exception. periodt. And this setting has no effect on "encode" (yet). 🫢

If you pass no argument, the limit check gets deactivated (same vibe as passing 0).

See "SECURITY CONSIDERATIONS" in JSON::XS for more info on why this is useful. πŸ”₯

πŸ”„ encode

$json_text = $json->encode($perl_scalar)

Converts the given Perl value or data structure into its JSON representation. Croaks on error. πŸ’€ That's the whole thing, she's simple.

πŸ” decode

$perl_scalar = $json->decode($json_text)

The literal opposite of "encode": she expects a JSON text, tries to parse it, and hands you back the resulting simple scalar or reference. Croaks on error. πŸ’–

βœ‚οΈ decode_prefix

($perl_scalar, $characters) = $json->decode_prefix($json_text)

Works just like the "decode" method, but here's the plot twist: instead of raising an exception when there's trailing garbage after the first JSON object, she will silently stop parsing right there and return the number of characters consumed so far. 😌

Super useful if your JSON texts aren't delimited by some outer protocol and you genuinely need to know where the JSON text ends. iykyk.

JSON::PP->new->decode_prefix ("[1] the tail")
=> ([1], 3)

🌈 FLAGS FOR JSON::PP ONLY 🌈

Okay so the following flags and properties are for JSON::PP only. πŸŽ€ If you use any of these, you can't make your application run faster by swapping JSON::PP out for JSON::XS. sorry bestie, that's just the deal.

If you need these and a speed boost, you might wanna try Cpanel::JSON::XS, a fork of JSON::XS by Reini Urban, which supports some of these (with a different set of incompatibilities). πŸ’…

And real talk: most of these historical flags are only kept around for backward compatibility, and should not be used in a new application. periodt.

🌸 allow_singlequote

$json = $json->allow_singlequote([$enable])
$enabled = $json->get_allow_singlequote

If $enable is true (or missing), then "decode" will accept invalid JSON texts containing strings that begin and end with single quotation marks. "encode" is not affected in any way, she doesn't care. πŸ™ˆ

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

$json->allow_singlequote->decode(qq|{"foo":'bar'}|);
$json->allow_singlequote->decode(qq|{'foo':"bar"}|);
$json->allow_singlequote->decode(qq|{'foo':'bar'}|);

πŸŽ€ allow_barekey

$json = $json->allow_barekey([$enable])
$enabled = $json->get_allow_barekey

If $enable is true (or missing), then "decode" will accept invalid JSON texts containing JSON objects whose names don't begin and end with quotation marks. "encode" is not affected in any way. πŸ¦‹

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

$json->allow_barekey->decode(qq|{foo:"bar"}|);

πŸ”’ allow_bignum

$json = $json->allow_bignum([$enable])
$enabled = $json->get_allow_bignum

If $enable is true (or missing), then "decode" will convert big integers that Perl can't handle as an integer into Math::BigInt objects, and convert floating numbers into Math::BigFloat objects. And "encode" will convert "Math::BigInt" and "Math::BigFloat" objects back into JSON numbers. it's giving big brain energy fr fr. 🧠✨

$json->allow_nonref->allow_bignum;
$bigfloat = $json->decode('2.000000000000000000000000001');
print $json->encode($bigfloat);
# => 2.000000000000000000000000001

See also MAPPING.

😌 loose

$json = $json->loose([$enable])
$enabled = $json->get_loose

If $enable is true (or missing), then "decode" will accept invalid JSON texts containing unescaped [\x00-\x1f\x22\x5c] characters. "encode" is not affected in any way. πŸ’…

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

$json->loose->decode(qq|["abc
                               def"]|);

βš”οΈ escape_slash

$json = $json->escape_slash([$enable])
$enabled = $json->get_escape_slash

If $enable is true (or missing), then "encode" will explicitly escape slash (solidus; "U+002F") characters, to reduce the risk of XSS (cross site scripting) that may be caused by "</script>" sitting inside a JSON text β€” with the cost of bloating the size of JSON texts. trade-offs, bestie. 😭

This option may be useful when you embed JSON in HTML, but embedding arbitrary JSON in HTML (by some HTML template toolkit or by string interpolation) is risky in general. You must escape the necessary characters in the correct order, depending on the context. no shortcuts. 🫢

"decode" will not be affected in any way. πŸ’–

πŸ“ indent_length

$json = $json->indent_length($number_of_spaces)
$length = $json->get_indent_length

This option is only useful when you also enable "indent" or "pretty". πŸŽ€

JSON::XS indents with three spaces when you "encode" (if requested by "indent" or "pretty"), and the number cannot be changed. JSON::PP, being the flexible queen she is, lets you change/get the number of indent spaces with this mutator/accessor. πŸ‘‘

The default number of spaces is three (same as JSON::XS), and the acceptable range is from 0 (no indentation; it'd be better to disable indentation by indent(0)) to 15. don't push your luck past 15. πŸ’…

πŸ”€ sort_by

$json = $json->sort_by($code_ref)
$json = $json->sort_by($subroutine_name)

If you just wanna sort keys (names) in JSON objects when you "encode", enable the "canonical" option (see above) β€” that lets you sort object keys alphabetically. easy. ✨

But if you do need to sort non-alphabetically for whatever reasons, you can hand a code reference (or a subroutine name) to "sort_by", and then that argument gets passed to Perl's sort built-in function. πŸ¦‹

Since the sorting is done in the JSON::PP scope, you usually need to prepend "JSON::PP::" to the subroutine name, plus the special variables $a and $b that "sort" uses in that subroutine. iykyk. πŸ’…

Example:

my %ORDER = (id => 1, class => 2, name => 3);
$json->sort_by(sub {
    ($ORDER{$JSON::PP::a} // 999) <=> ($ORDER{$JSON::PP::b} // 999)
    or $JSON::PP::a cmp $JSON::PP::b
});
print $json->encode([
    {name => 'CPAN', id => 1, href => 'http://cpan.org'}
]);
# [{"id":1,"name":"CPAN","href":"http://cpan.org"}]
Note that "sort_by" affects all the plain hashes in the data structure. If you need finer control, "tie" the necessary hashes with a module that implements an ordered hash (such as Hash::Ordered and Tie::IxHash). "canonical" and "sort_by" don't affect the key order in "tie"d hashes. πŸ™ˆ
use Hash::Ordered;
tie my %hash, 'Hash::Ordered',
    (name => 'CPAN', id => 1, href => 'http://cpan.org');
print $json->encode([\%hash]);
# [{"name":"CPAN","id":1,"href":"http://cpan.org"}] # order is kept

πŸ’– INCREMENTAL PARSING πŸ’–

okay so this section is also taken from JSON::XS, and it's lowkey one of the coolest parts.

sometimes you don't have your whole JSON text sitting there ready β€” you've got a stream, and you need to nibble at it. now, heads up bestie: this module always has to keep the JSON text and the resulting Perl data structure in memory at the same time. that's just how it is. but it does let you parse a JSON stream incrementally. it does that by accumulating text until it's got a whole complete JSON object, and then it decodes that. this is similar to using decode_prefix to check whether a full JSON object is available yet, except this is way more efficient, and you can do it with the absolute minimum number of method calls. slay.

JSON::PP will only try to parse the JSON text once it's sure it has enough text to get a decisive result β€” it uses a very simple but truly incremental parser. which means sometimes it won't stop as early as the full parser would. for example, it doesn't detect mismatched parentheses. the one thing it guarantees is that it starts decoding as soon as a syntactically valid JSON text has been seen. so because of that, you need to set resource limits (like max_size) to make sure the parser actually stops parsing when there are syntax errors. for real. 🫢

the following methods implement this incremental parser.

incr_parse

$json->incr_parse( [$string] ) # void context

$obj_or_undef = $json->incr_parse( [$string] ) # scalar context

@obj_or_empty = $json->incr_parse( [$string] ) # list context

this is the main character of parsing functions, the central one. it can append new text and extract objects from the stream accumulated so far β€” and both of those jobs are optional, she's flexible like that.

if $string is given, that string gets appended to the JSON fragment that's already stored in the $json object.

after that, if the function is called in void context, it just returns and doesn't do anything else. you use this to add more text in as many chunks as you want. very chill.

if the method is called in scalar context, it tries to extract exactly one JSON object. if that works, it returns that object, otherwise it returns undef. and if there's a parse error, this method will croak exactly like decode does β€” in that case you can use incr_skip to skip over the bad part. this is the most common way to use this method, no cap.

and finally, in list context, it tries to extract as many objects from the stream as it can find and return them, or the empty list if there's nothing. for this to work there must be no separators (other than whitespace) between the JSON objects or arrays β€” they have to be concatenated back-to-back. if an error happens, an exception gets raised just like 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.

my @objs = JSON::PP->new->incr_parse ("[5][7][1,2]");

incr_text

$lvalue_string = $json->incr_text

this method returns the currently stored JSON fragment as an lvalue β€” meaning yes, you can manipulate it. but 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. even if in simple tests it seems to actually work, it will fail under real world conditions. as a special exception, you can also call this method before you've parsed anything at all.

so basically: you can only use this function to look at or manipulate text before or after complete JSON objects. not while the parser is in the middle of parsing one.

this function is useful in two cases: a) finding the trailing text after a JSON object, or b) parsing multiple JSON objects that are separated by non-JSON text (like commas).

incr_skip

$json->incr_skip

this resets the state of the incremental parser and removes the parsed text from the input buffer so far. super useful after incr_parse died β€” because when that happens, the input buffer and the incremental parser state are left unchanged. so this lets you skip the text parsed so far and reset the parse state.

the difference from incr_reset is that only the text up until the parse error occurred gets removed. πŸ’…

incr_reset

$json->incr_reset

this completely resets the incremental parser. like, after this call it's as if the parser had never parsed anything at all. memory: wiped. fresh start energy. ✨

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 every successful decode.


πŸ¦‹ MAPPING πŸ¦‹

most of this section is also taken from JSON::XS. 🫢

this section describes how JSON::PP maps Perl values to JSON values and vice versa. these mappings are designed to "do the right thing" in most circumstances automatically, and they preserve round-tripping characteristics β€” what you put in comes out as something equivalent.

for the more enlightened among us: in the descriptions below, lowercase perl means the Perl interpreter, while uppercase Perl means the abstract Perl language itself.

🌈 JSON -> PERL 🌈

  • object β€” a JSON object becomes a reference to a hash in Perl. no ordering of object keys is preserved (JSON does not preserve object key ordering itself).
  • array β€” a JSON array becomes a reference to an array in Perl.
  • string β€” a JSON string becomes a string scalar in Perl. Unicode codepoints in JSON are represented by the same codepoints in the Perl string, so no manual decoding is necessary. iconic.
  • number β€” 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's no difference between those, because 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::PP 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's possible without loss of precision. otherwise it will preserve the number as a string value β€” in which case you lose roundtripping ability, since 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::PP only guarantees precision up to but not including the least significant bit.

when allow_bignum is enabled, big integer values and any numeric values will be converted into Math::BigInt and Math::BigFloat objects respectively, without becoming string scalars or losing precision.

  • true, false β€” these JSON atoms become JSON::PP::true and JSON::PP::false, respectively. they're 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::PP::is_bool function.
  • null β€” a JSON null atom becomes undef in Perl.
  • shell-style comments ("# text") β€” as a nonstandard extension to the JSON syntax that's enabled by the relaxed setting, shell-style comments are allowed. they can start anywhere outside strings and go till the end of the line.
  • tagged values ("(tag)value"). β€” another nonstandard extension to the JSON syntax, enabled with the allow_tags setting, are tagged values. in this implementation, the tag must be a perl package/class name encoded as a JSON string, and the value must be a JSON array encoding optional constructor arguments.

see "OBJECT SERIALISATION", below, for details.

πŸ’œ PERL -> JSON πŸ’œ

the mapping from Perl to JSON is a bit more difficult, since Perl is a truly typeless language β€” so we can only guess which JSON type is meant by a Perl value. bestie it's giving mystery box.

  • hash references β€” Perl hash references become JSON objects. since there's no inherent ordering in hash keys (or JSON objects), they'll usually be encoded in a pseudo-random order. JSON::PP can optionally sort the hash keys (determined by the canonical flag and/or the sort_by property), so the same data structure will serialise to the same JSON text (given the same settings and version of JSON::PP) β€” 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.
  • array references β€” Perl array references become JSON arrays.
  • other references β€” other unblessed references are generally not allowed and will cause an exception to be thrown. the exception is references to the integers 0 and 1, which get turned into false and true atoms in JSON. you can also use JSON::PP::false and JSON::PP::true to improve readability.
to_json [\0, JSON::PP::true]      # yields [false,true]
  • JSON::PP::true, JSON::PP::false β€” these special values become JSON true and JSON false values, respectively. you can also use \1 and \0 directly if you want.
  • JSON::PP::null β€” this special value becomes JSON null.
  • blessed objects β€” blessed objects are not directly representable in JSON, but JSON::PP allows various ways of handling objects. see "OBJECT SERIALISATION", below, for details.
  • simple scalars β€” simple Perl scalars (any scalar that is not a reference) are the most difficult objects to encode. 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:
# dump as number
encode_json [2]                      # yields [2]
encode_json [-3.0e17]                # yields [-3e+17]
my $value = 5; encode_json [$value]  # yields [5]

# used as string, so dump as string
print $value;
encode_json [$value]                 # yields ["5"]

# undef becomes null
encode_json [undef]                  # yields [null]

you can force the type to be a JSON string by stringifying it:

my $x = 3.1; # some variable containing a number
"$x";        # stringified
$x .= "";    # another, more awkward way to stringify
print $x;    # perl does it for you, too, quite often
             # (but for older perls)

you can force the type to be a JSON number by numifying it:

okay so if you need to force a scalar to be a number, this is literally the move:

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.

and that's kinda it bestie 😭 you can not currently force the type in other, less obscure, ways. that's the whole menu.

<div></div>

since version 2.91_01, JSON::PP uses a whole different number detection logic that converts a scalar that is possible to turn into a number safely. the new logic is slightly faster, and tends to help people who use older perl or who want to encode complicated data structure. but β€” and this is the plot twist β€” this may results in a different JSON text from the one JSON::XS encodes (and thus may break tests that compare entire JSON texts). if you genuinely do need the previous behavior for compatibility or for finer control, set PERL_JSON_PP_USE_B environmental variable to true before you use JSON::PP (or JSON.pm). periodt.

ngl, 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. πŸ’€

and here's the trust thing, bc it's giving very much "we are not your babysitter": JSON::PP (and JSON::XS) trusts what you pass to encode method (or encode_json function) is a clean, validated data structure with values that can be represented as valid JSON values only, because it's not from an external data source (as opposed to JSON texts you pass to decode or decode_json, which JSON::PP considers tainted and doesn't trust). as JSON::PP doesn't know exactly what you and consumers of your JSON texts want the unexpected values to be (you may want to convert them into null, or to stringify them with or without normalisation (string representation of infinities/NaN may vary depending on platforms), or to croak without conversion), you're advised to do what you and your consumers need before you encode, and also not to numify values that may start with values that look like a number (including infinities/NaN), without validating. 🫢


πŸ¦‹ OBJECT SERIALISATION πŸ¦‹

ok so JSON cannot directly represent Perl objects, which means you have to choose between:

  • a pure JSON representation (without the ability to deserialise the object automatically again), and
  • a nonstandard extension to the JSON syntax, tagged values.

✨ SERIALISATION ✨

what happens when JSON::PP encounters a Perl object depends on the allow_blessed, convert_blessed, allow_tags and allow_bignum settings, which are used in this order:

  1. allow_tags is enabled and the object has a FREEZE method.

in this case, JSON::PP creates a tagged JSON value, using a nonstandard extension to the JSON syntax.

this works by invoking the FREEZE method on the object, with the first argument being the object to serialise, and the second argument being the constant string JSON to distinguish it from other serialisers.

the FREEZE method can return any number of values (i.e. zero or more). these values and the package/classname of the object will then be encoded as a tagged JSON value in the following format:

("classname")[FREEZE return values...]

e.g.:

("URI")["http://www.google.com/"]
("MyDate")[2013,10,29]
("ImageData::JPEG")["Z3...VlCg=="]

for example, the hypothetical My::Object FREEZE method might use the objects type and id members to encode the object:

sub My::Object::FREEZE {
   my ($self, $serialiser) = @_;

   ($self->{type}, $self->{id})
}
  1. convert_blessed is enabled and the object has a TO_JSON method.

in this case, the TO_JSON method of the object is invoked in scalar context. it must return a single scalar that can be directly encoded into JSON. this scalar replaces the object in the JSON text.

for example, the following TO_JSON method will convert all URI objects to JSON strings when serialised. the fact that these values originally were URI objects is lost. 🫠

sub URI::TO_JSON {
   my ($uri) = @_;
   $uri->as_string
}
  1. allow_bignum is enabled and the object is a Math::BigInt or Math::BigFloat.

the object will be serialised as a JSON number value.

  1. allow_blessed is enabled.

the object will be serialised as a JSON null value.

  1. none of the above

if none of the settings are enabled or the respective methods are missing, JSON::PP throws an exception. 😭 no vibes, only error.

πŸ’œ DESERIALISATION πŸ’œ

for deserialisation there are only two cases to consider: either nonstandard tagging was used, in which case allow_tags decides, or objects cannot be automatically be deserialised, in which case you can use postprocessing or the filter_json_object or filter_json_single_key_object callbacks to get some real objects our of your JSON.

this section only considers the tagged value case: a tagged JSON object is encountered during decoding and allow_tags is disabled, a parse error will result (as if tagged values were not part of the grammar).

if allow_tags is enabled, JSON::PP will look up the THAW method of the package/classname used during serialisation (it will not attempt to load the package as a Perl module). if there is no such method, the decoding will fail with an error.

otherwise, the THAW method is invoked with the classname as first argument, the constant string JSON as second argument, and all the values from the JSON array (the values originally returned by the FREEZE method) as remaining arguments.

the method must then return the object. while technically you can return any Perl scalar, you might have to enable the allow_nonref setting to make that work in all cases, so better return an actual blessed reference. πŸ‘‘

as an example, let's implement a THAW function that regenerates the My::Object from the FREEZE example earlier:

sub My::Object::THAW {
   my ($class, $serialiser, $type, $id) = @_;

   $class->new (type => $type, id => $id)
}

and that's the whole freeze/thaw glow-up bestie, the object goes out one way and comes back the same way ✨

🌈 ENCODING/CODESET FLAG NOTES 🌈

okay bestie, this whole section is lifted from JSON::XS, so credit where credit is due πŸ’…

If you're the curious type (and I know you are), you've probably clocked that there are a bunch of flags out there that have to do with encodings and codesets β€” namely utf8, latin1 and ascii. And yeah, people get hella confused about what each one actually does, so here's the quick comparison so you can stop guessing:

utf8 is the one that controls whether the JSON text that encode spits out (and the text decode expects to get) is UTF-8 encoded or not. Meanwhile latin1 and ascii only control whether encode escapes character values that fall outside their respective codeset range. And here's the thing β€” none of these flags conflict with each other, even though honestly some combinations make way less sense than others πŸ™ˆ

The devs were super careful to make all the flags symmetrical between encode and decode β€” so basically, any text you encode with any combo of these flag values will decode correctly as long as you use the same flags. So like, if you're using different flag settings when encoding vs. decoding, bestie... you probably have a bug somewhere 😭

And now the verbose rundown. Real quick though, a "codeset" is just an abstract set of character-codepoint pairs, while an encoding takes those codepoint numbers and actually encodes them β€” in our case, into octets. Unicode is (among other things) a codeset, UTF-8 is an encoding, and ISO-8859-1 (= latin 1) and ASCII are both codesets and encodings at the same time, which is exactly the kind of thing that makes people's brains short-circuit πŸ’€


πŸ¦‹ utf8 flag disabled

When utf8 is disabled (which is the default, bestie), then encode/decode generate and expect Unicode strings. Translation: characters with high ordinal Unicode values (> 255) get encoded as those actual characters, and likewise those characters just decode as-is. Nothing gets changed about them, except that they get "(re-)interpreting" as Unicode codepoints or Unicode characters respectively β€” and to Perl, those two things are literally the same thing in strings, unless you're out here doing funny/weird/dumb stuff πŸ‘‘

This is the move when you want to do the encoding yourself (say, when you want UTF-16 encoded JSON texts), or when some other layer handles the encoding for you. Like, if you're printing to a terminal using a filehandle that transparently encodes to UTF-8, you absolutely do NOT want to UTF-8 encode your data first and then have Perl encode it another time. That's just double encoding, and no one wants that 🌸

✨ utf8 flag enabled

If the utf8 flag is on, encode/decode will encode all characters using the corresponding UTF-8 multi-byte sequence, and will expect your input strings to be encoded as UTF-8. Which means no "character" of the input string must have any value > 255, because UTF-8 simply does not allow that.

So the utf8 flag is basically flipping between two modes:

  • disabled β†’ you get a Unicode string in Perl
  • enabled β†’ you get a UTF-8 encoded octet/binary string in Perl

slay, two modes, pick your fighter πŸ’…

πŸŽ€ latin1 or ascii flags enabled

With latin1 (or ascii) enabled, encode will escape characters with ordinal values > 255 (> 127 with ascii) and encode the remaining characters as specified by the utf8 flag.

If utf8 is disabled, then the result is also correctly encoded in those character sets β€” because both are proper subsets of Unicode, meaning a Unicode string with all character values < 256 is the same thing as an ISO-8859-1 string, and a Unicode string with all character values < 128 is the same thing as an ASCII string in Perl. cute, right? 🫢

If utf8 is enabled, you still get a correct UTF-8-encoded string regardless of these flags β€” it's just that some more characters will get escaped using \uXXXX than before.

Now, important caveat, bestie: ISO-8859-1-encoded strings are NOT compatible with UTF-8 encoding, while ASCII-encoded strings are. Why? Because the ISO-8859-1 encoding is NOT a subset of UTF-8 (even though the ISO-8859-1 codeset is a subset of Unicode), while ASCII is. Iconic levels of technicality tbh.

And here's the plot twist that surprises everyone: decode will ignore these flags and treat all input values as governed by the utf8 flag. If it's disabled, that lets you decode ISO-8859-1- and ASCII-encoded strings, since both are strict subsets of Unicode. If it's enabled, you can correctly decode UTF-8 encoded strings. the way that decode just does its own thing... πŸ’€

So neither latin1 nor ascii is incompatible with the utf8 flag β€” they only govern when the JSON output engine escapes a character or not.

The main use for latin1 is to relatively efficiently store binary data as JSON β€” at the expense of breaking compatibility with most JSON decoders 😭

The main use for ascii is to force the output to not contain characters with values > 127. That means you can interpret the resulting string as UTF-8, ISO-8859-1, ASCII, KOI8-R or most about any character set and 8-bit-encoding, and still get the same data structure back. Super useful when your channel for JSON transfer isn't 8-bit clean, or when the encoding might get mangled in between (e.g. in mail). It works because ASCII is a proper subset of most 8-bit and multibyte encodings in use in the world. no cap πŸ‘‘


πŸ’€ BUGS

Found a bug in a specific behavior of this module? Please report it on RT or GitHub issues (preferred):

As for new features and requests to change common behaviors β€” bestie, please ask the author of JSON::XS (Marc Lehmann, <schmorp[at]schmorp.de>) first, by email (important!), to keep compatibility among JSON.pm backends. yes this is a real ask, do it πŸ™

And generally speaking? If you need something special just for you, you're advised to create a new module, maybe based on JSON::Tiny, which is smaller and written in a much cleaner way than this module. do with that information what you will πŸ’…


πŸ‘€ SEE ALSO


🌸 AUTHOR

Makamaka Hannyaharamitu, <makamaka[at]cpan.org>

πŸ’– CURRENT MAINTAINER

Kenichi Ishigaki, <ishigaki[at]cpan.org>


Copyright 2007-2016 by Makamaka Hannyaharamitu

Most of the documentation is taken from JSON::XS by Marc Lehmann

This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.


and that's a wrap on JSON::PP bestie πŸŽ€ go forth and encode responsibly, you got this πŸ’œ

source: perl, version v5.44.0 β€” dated 2026-10-17 β€” page JSON::PP(3perl)

πŸ“¦ where this page comes from
  • arch rolling: perl 5.44.0-1 Β· Artistic-1.0-Perl AND GPL-1.0-or-later
  • πŸ’– girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms