Cpanel::JSON::XS โ cPanel fork of JSON::XS, fast and correct serializing
| Use Case | Command | Description |
|---|---|---|
| โญ Encode Perl to JSON (UTF-8) | encode_json $data | Converts Perl data structure to UTF-8 JSON string |
| โญ Decode JSON to Perl | decode_json $json_text | Parses UTF-8 JSON string to Perl structure |
| ๐ ๏ธ OO coder with options | Cpanel::JSON::XS->new->utf8->pretty->encode($data) | Create configurable encoder/decoder |
| ๐ Check boolean | Cpanel::JSON::XS::is_bool($scalar) | Returns true if scalar is JSON true/false |
| ๐ Safe decode (no refs) | $json->allow_nonref(0)->decode($text) | Reject non-array/object top-level values |
| ๐ Limit nesting depth | $json->max_depth(512) | Prevent stack overflow |
| ๐ฆ Limit text size | $json->max_size(1000000) | Reject overly large JSON texts |
| ๐งน Pretty-print | $json->pretty->encode($data) | Human-readable indented output |
| ๐ค ASCII-only output | $json->ascii->encode($data) | Escapes non-ASCII characters |
| ๐ก Latin1 output | $json->latin1->encode($data) | Escapes only characters > 255 |
| ๐ข Binary (raw bytes) | $json->binary->encode($data) | No UTF-8 detection, uses \xNN escapes |
| ๐ Incremental parsing | $json->incr_parse($chunk) | Parse JSON from stream |
| ๐ท๏ธ Object serialization | $json->allow_tags->encode($obj) | Encode perl objects via FREEZE/THAW |
use Cpanel::JSON::XS;
# 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
$coder = Cpanel::JSON::XS->new->ascii->pretty->allow_nonref;
$pretty_printed_unencoded = $coder->encode ($perl_scalar);
$perl_scalar = $coder->decode ($unicode_json_text);
# Note that 5.6 misses most smart utf8 and encoding functionalities
# of newer releases.
# Note that JSON::MaybeXS will automatically use Cpanel::JSON::XS
# if available, at virtually no speed overhead either, so you should
# be able to just:
use JSON::MaybeXS;
# and do the same things, except that you have a pure-perl fallback now.
Note that this module will be replaced by a new JSON::Safe module soon,
with the same API just guaranteed safe defaults.
This module converts Perl data structures to JSON and vice versa. Its primary goal is to be correct and its secondary goal is to be fast. To reach the latter goal it was written in C.
As this is the n-th-something JSON module on CPAN, what was the reason to write yet another JSON module? While it seems there are many JSON modules, none of them correctly handle all corner cases, and in most cases their maintainers are unresponsive, gone missing, or not listening to bug reports for other reasons.
See below for the cPanel fork.
See MAPPING, below, on how Cpanel::JSON::XS maps perl values to JSON values and vice versa.
Since the original author MLEHMANN has no public bugtracker, this cPanel fork sits on GitHub.
Source: https://github.com/rurban/Cpanel-JSON-XS | Original: http://cvs.schmorp.de/JSON-XS/
Changes from JSON::XS:
decode_json() โ non-refs disallowed (optional 2nd arg)null, optional stringify_infnan()binary extension for \xNN and \NNN sequences!0 โ true, !1 โ falseThe following convenience methods are exported by default:
$json_text = encode_json $perl_scalar, [json_type]Converts Perl data to UTF-8 encoded JSON string. Croaks on error. Equivalent to Cpanel::JSON::XS->new->utf8->encode($perl_scalar, $json_type) but faster.
$perl_scalar = decode_json $json_text [, $allow_nonref [, my $json_type ] ]Parses UTF-8 JSON string to Perl data. Croaks on error. Optional $allow_nonref (default false) allows top-level scalars per RFC 7159. Equivalent to Cpanel::JSON::XS->new->utf8->decode($json_text, $json_type) but faster.
$is_boolean = Cpanel::JSON::XS::is_bool $scalarReturns true if the scalar is a JSON boolean (JSON::PP::true/false, or from JSON::XS).
from_json โ renamed to decode_jsonto_json โ renamed to encode_jsonSince this often leads to confusion, here are a few very clear words on how Unicode works in Perl, modulo bugs.
The object oriented interface lets you configure your own encoding or decoding style.
$json = new Cpanel::JSON::XSCreates a new JSON object. All boolean flags are disabled by default. Mutators return the JSON object, allowing chaining.
$json = $json->ascii ([$enable]) โ Encode with only ASCII characters (escape high Unicode)$json = $json->latin1 ([$enable]) โ Encode as Latin1 (escape characters > 255)$json = $json->binary ([$enable]) โ No UTF-8 detection; use \xNN escapes for bytes$json = $json->utf8 ([$enable]) โ Encode/decode as UTF-8 bytes$json = $json->pretty ([$enable]) โ Enable indent, space_before, space_after$json = $json->indent ([$enable]) โ Multiline output with indentation$json = $json->indent_length([$number_of_spaces]) โ Set indent length (0-15, default 3)$json = $json->space_before ([$enable]) โ Add space before colon$json = $json->space_after ([$enable]) โ Add space after colon and comma$json = $json->relaxed ([$enable]) โ Accept trailing commas, shell comments, literal TAB, single quotes, bare keys, duplicate keys$json = $json->canonical ([$enable]) โ Sort object keys for deterministic output$json = $json->sort_by (undef, 0, 1 or a block) โ Currently only sets canonical$json = $json->escape_slash ([$enable]) โ Escape forward slashes as \/$json = $json->unblessed_bool ([$enable]) โ Return plain 1/0 instead of JSON::PP::Boolean objects$json = $json->allow_singlequote ([$enable]) โ Accept single quotes for strings$json = $json->allow_barekey ([$enable]) โ Accept unquoted object keys$json = $json->allow_bignum ([$enable]) โ Convert large numbers to Math::BigInt/BigFloat$json = $json->allow_nonref ([$enable]) โ Allow non-reference top-level values$json = $json->allow_unknown ([$enable]) โ Encode unrepresentable values as null$json = $json->allow_stringify ([$enable]) โ Stringify non-object values$json = $json->require_types ([$enable]) โ Require explicit type specification$json = $json->type_all_string ([$enable]) โ Encode all scalars as strings$json = $json->allow_dupkeys ([$enable]) โ Allow duplicate hash keys$json = $json->allow_blessed ([$enable]) โ Encode blessed references (see convert_blessed)$json = $json->convert_blessed ([$enable]) โ Call TO_JSON or stringification overload on objects$json = $json->allow_tags ([$enable]) โ Enable FREEZE/THAW object serialization$json = $json->filter_json_object ([$coderef]) โ Transform decoded objects via callback$json = $json->filter_json_single_key_object ($key => $coderef) โ Transform single-key objects$json = $json->shrink ([$enable]) โ Minimize memory usage of strings$json = $json->max_depth ([$maximum_nesting_depth]) โ Set maximum nesting depth (default 512)$json = $json->max_size ([$maximum_string_size]) โ Set maximum JSON text size (0 = no limit)$json->stringify_infnan ([$infnan_mode = 1]) โ How to encode inf/nan: 0=null, 1=stringified, 2=pass through, 3=inf/-inf/nan strings$json_text = $json->encode ($perl_scalar, $json_type)Converts Perl data to JSON string. For type argument see Cpanel::JSON::XS::Type.
$perl_scalar = $json->decode ($json_text, my $json_type)Parses JSON string to Perl data. Croaks on error.
($perl_scalar, $characters) = $json->decode_prefix ($json_text)Like decode, but returns number of characters consumed, allowing trailing garbage.
$json->to_json ($perl_hash_or_arrayref) โ Use encode_json instead$json->from_json ($utf8_encoded_json_text) โ Use decode_json insteadAllows parsing JSON streams. Methods:
$json->incr_parse ([$string]) โ Append text and/or extract objects$lvalue_string = $json->incr_text โ Access current buffer (Perl >= 5.8)$json->incr_skip โ Remove parsed text after error$json->incr_reset โ Reset parser completelyLimitations: allow_nonref not supported; numbers cannot be incrementally parsed.
Simple prefix extraction:
my $text = "[1,2,3] hello";
my $json = new Cpanel::JSON::XS;
my $obj = $json->incr_parse ($text);
my $tail = $json->incr_text;
# $tail now contains " hello"
Multiple objects from TCP stream:
my $json = new Cpanel::JSON::XS;
while (sysread $socket, my $buf, 4096) {
for my $request ($json->incr_parse ($buf)) {
# act on $request
}
}
Parsing comma-separated objects:
my $text = "[1],[2], [3]";
my $json = new Cpanel::JSON::XS;
$json->incr_parse ($text);
while (my $obj = $json->incr_parse) {
# do something
$json->incr_text =~ s/^ \s* , //x;
}
Gigantic array-of-objects: See full man page for detailed example with manual [ parsing and element extraction.
Detects Unicode Byte Order Marks (UTF-8, UTF-16LE, UTF-16BE, UTF-32LE, UTF-32BE) on decode. BOM handling is per-call, does not change object state. Older Perl (< 5.20) requires loading Encode module for multi-byte BOMs. RFC 7159 recommends UTF-8 only; future versions may reject UTF-16/32 BOMs.
Precedence: allow_tags (FREEZE) โ convert_blessed (TO_JSON) โ stringification overload โ allow_blessed (null) โ exception. Deserialization via THAW method when allow_tags enabled.
Flags control output encoding and escaping:
These flags are symmetric: encode with same flags as decode for correct round-trip.
Cpanel::JSON::XS is the only known JSON decoder that passes all seriot.ch tests while being the fastest. It accepts booleans from JSON::XS, JSON::PP, and Mojo::JSON. For interoperability, load JSON and JSON::XS before Cpanel::JSON::XS to handle boolean objects correctly.
Tagged value syntax (allow_tags) can be converted to standard JSON arrays via regex for compatibility with other decoders.
RFC 7159 allows top-level scalars. For security, Cpanel::JSON::XS defaults to RFC 4627 (no scalars). Use ->allow_nonref to enable RFC 7159 behavior. Future versions may change the default; application authors should explicitly set allow_nonref(0) if they need strict mode.
JSON is inherently secure compared to other serializers because it does not deserialize objects by default. However, always:
max_sizemax_depth (default 512)allow_tags or convert_blessed with untrusted inputOld JSON (RFC 4627) requires top-level array or object. New JSON (RFC 7159) allows scalars. For security, the default remains old. To enable new: my $json = JSON::XS->new->allow_nonref;
Cpanel::JSON::XS supports ithreads (unlike JSON::XS). Report any thread-related bugs.
Report issues at GitHub. The original JSON::XS author prefers private emails; please report both places for cross-fix.
This module is available under the same licenses as Perl: Artistic License and GPL.
cpanel_json_xs command line utilityReini Urban <rurban@cpan.org>
Marc Lehmann <schmorp@schmorp.de>, http://home.schmorp.de/
Reini Urban <rurban@cpan.org>
Generated by phpman v4.9.27 · Markdown · JSON · MCP Author: Che Dong Under GNU General Public License
2026-07-17 14:12 @216.73.216.114
CrawledBy Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; ClaudeBot/1.0; +claudebot@anthropic.com)
Enhanced by LLM: deepseek-v4-flash / taotoken.net / www.chedong.com - original format