| 1 |
NAME |
| 2 |
JSON::XS - JSON serialising/deserialising, done correctly and fast |
| 3 |
|
| 4 |
SYNOPSIS |
| 5 |
use JSON::XS; |
| 6 |
|
| 7 |
# exported functions, they croak on error |
| 8 |
# and expect/generate UTF-8 |
| 9 |
|
| 10 |
$utf8_encoded_json_text = to_json $perl_hash_or_arrayref; |
| 11 |
$perl_hash_or_arrayref = from_json $utf8_encoded_json_text; |
| 12 |
|
| 13 |
# OO-interface |
| 14 |
|
| 15 |
$coder = JSON::XS->new->ascii->pretty->allow_nonref; |
| 16 |
$pretty_printed_unencoded = $coder->encode ($perl_scalar); |
| 17 |
$perl_scalar = $coder->decode ($unicode_json_text); |
| 18 |
|
| 19 |
DESCRIPTION |
| 20 |
This module converts Perl data structures to JSON and vice versa. Its |
| 21 |
primary goal is to be *correct* and its secondary goal is to be *fast*. |
| 22 |
To reach the latter goal it was written in C. |
| 23 |
|
| 24 |
As this is the n-th-something JSON module on CPAN, what was the reason |
| 25 |
to write yet another JSON module? While it seems there are many JSON |
| 26 |
modules, none of them correctly handle all corner cases, and in most |
| 27 |
cases their maintainers are unresponsive, gone missing, or not listening |
| 28 |
to bug reports for other reasons. |
| 29 |
|
| 30 |
See COMPARISON, below, for a comparison to some other JSON modules. |
| 31 |
|
| 32 |
See MAPPING, below, on how JSON::XS maps perl values to JSON values and |
| 33 |
vice versa. |
| 34 |
|
| 35 |
FEATURES |
| 36 |
* correct unicode handling |
| 37 |
This module knows how to handle Unicode, and even documents how and |
| 38 |
when it does so. |
| 39 |
|
| 40 |
* round-trip integrity |
| 41 |
When you serialise a perl data structure using only datatypes |
| 42 |
supported by JSON, the deserialised data structure is identical on |
| 43 |
the Perl level. (e.g. the string "2.0" doesn't suddenly become "2" |
| 44 |
just because it looks like a number). |
| 45 |
|
| 46 |
* strict checking of JSON correctness |
| 47 |
There is no guessing, no generating of illegal JSON texts by |
| 48 |
default, and only JSON is accepted as input by default (the latter |
| 49 |
is a security feature). |
| 50 |
|
| 51 |
* fast |
| 52 |
Compared to other JSON modules, this module compares favourably in |
| 53 |
terms of speed, too. |
| 54 |
|
| 55 |
* simple to use |
| 56 |
This module has both a simple functional interface as well as an OO |
| 57 |
interface. |
| 58 |
|
| 59 |
* reasonably versatile output formats |
| 60 |
You can choose between the most compact guarenteed single-line |
| 61 |
format possible (nice for simple line-based protocols), a pure-ascii |
| 62 |
format (for when your transport is not 8-bit clean, still supports |
| 63 |
the whole unicode range), or a pretty-printed format (for when you |
| 64 |
want to read that stuff). Or you can combine those features in |
| 65 |
whatever way you like. |
| 66 |
|
| 67 |
FUNCTIONAL INTERFACE |
| 68 |
The following convinience methods are provided by this module. They are |
| 69 |
exported by default: |
| 70 |
|
| 71 |
$json_text = to_json $perl_scalar |
| 72 |
Converts the given Perl data structure (a simple scalar or a |
| 73 |
reference to a hash or array) to a UTF-8 encoded, binary string |
| 74 |
(that is, the string contains octets only). Croaks on error. |
| 75 |
|
| 76 |
This function call is functionally identical to: |
| 77 |
|
| 78 |
$json_text = JSON::XS->new->utf8->encode ($perl_scalar) |
| 79 |
|
| 80 |
except being faster. |
| 81 |
|
| 82 |
$perl_scalar = from_json $json_text |
| 83 |
The opposite of "to_json": expects an UTF-8 (binary) string and |
| 84 |
tries to parse that as an UTF-8 encoded JSON text, returning the |
| 85 |
resulting simple scalar or reference. Croaks on error. |
| 86 |
|
| 87 |
This function call is functionally identical to: |
| 88 |
|
| 89 |
$perl_scalar = JSON::XS->new->utf8->decode ($json_text) |
| 90 |
|
| 91 |
except being faster. |
| 92 |
|
| 93 |
$is_boolean = JSON::XS::is_bool $scalar |
| 94 |
Returns true if the passed scalar represents either JSON::XS::true |
| 95 |
or JSON::XS::false, two constants that act like 1 and 0, |
| 96 |
respectively and are used to represent JSON "true" and "false" |
| 97 |
values in Perl. |
| 98 |
|
| 99 |
See MAPPING, below, for more information on how JSON values are |
| 100 |
mapped to Perl. |
| 101 |
|
| 102 |
OBJECT-ORIENTED INTERFACE |
| 103 |
The object oriented interface lets you configure your own encoding or |
| 104 |
decoding style, within the limits of supported formats. |
| 105 |
|
| 106 |
$json = new JSON::XS |
| 107 |
Creates a new JSON::XS object that can be used to de/encode JSON |
| 108 |
strings. All boolean flags described below are by default |
| 109 |
*disabled*. |
| 110 |
|
| 111 |
The mutators for flags all return the JSON object again and thus |
| 112 |
calls can be chained: |
| 113 |
|
| 114 |
my $json = JSON::XS->new->utf8->space_after->encode ({a => [1,2]}) |
| 115 |
=> {"a": [1, 2]} |
| 116 |
|
| 117 |
$json = $json->ascii ([$enable]) |
| 118 |
If $enable is true (or missing), then the "encode" method will not |
| 119 |
generate characters outside the code range 0..127 (which is ASCII). |
| 120 |
Any unicode characters outside that range will be escaped using |
| 121 |
either a single \uXXXX (BMP characters) or a double \uHHHH\uLLLLL |
| 122 |
escape sequence, as per RFC4627. The resulting encoded JSON text can |
| 123 |
be treated as a native unicode string, an ascii-encoded, |
| 124 |
latin1-encoded or UTF-8 encoded string, or any other superset of |
| 125 |
ASCII. |
| 126 |
|
| 127 |
If $enable is false, then the "encode" method will not escape |
| 128 |
Unicode characters unless required by the JSON syntax or other |
| 129 |
flags. This results in a faster and more compact format. |
| 130 |
|
| 131 |
The main use for this flag is to produce JSON texts that can be |
| 132 |
transmitted over a 7-bit channel, as the encoded JSON texts will not |
| 133 |
contain any 8 bit characters. |
| 134 |
|
| 135 |
JSON::XS->new->ascii (1)->encode ([chr 0x10401]) |
| 136 |
=> ["\ud801\udc01"] |
| 137 |
|
| 138 |
$json = $json->latin1 ([$enable]) |
| 139 |
If $enable is true (or missing), then the "encode" method will |
| 140 |
encode the resulting JSON text as latin1 (or iso-8859-1), escaping |
| 141 |
any characters outside the code range 0..255. The resulting string |
| 142 |
can be treated as a latin1-encoded JSON text or a native unicode |
| 143 |
string. The "decode" method will not be affected in any way by this |
| 144 |
flag, as "decode" by default expects unicode, which is a strict |
| 145 |
superset of latin1. |
| 146 |
|
| 147 |
If $enable is false, then the "encode" method will not escape |
| 148 |
Unicode characters unless required by the JSON syntax or other |
| 149 |
flags. |
| 150 |
|
| 151 |
The main use for this flag is efficiently encoding binary data as |
| 152 |
JSON text, as most octets will not be escaped, resulting in a |
| 153 |
smaller encoded size. The disadvantage is that the resulting JSON |
| 154 |
text is encoded in latin1 (and must correctly be treated as such |
| 155 |
when storing and transfering), a rare encoding for JSON. It is |
| 156 |
therefore most useful when you want to store data structures known |
| 157 |
to contain binary data efficiently in files or databases, not when |
| 158 |
talking to other JSON encoders/decoders. |
| 159 |
|
| 160 |
JSON::XS->new->latin1->encode (["\x{89}\x{abc}"] |
| 161 |
=> ["\x{89}\\u0abc"] # (perl syntax, U+abc escaped, U+89 not) |
| 162 |
|
| 163 |
$json = $json->utf8 ([$enable]) |
| 164 |
If $enable is true (or missing), then the "encode" method will |
| 165 |
encode the JSON result into UTF-8, as required by many protocols, |
| 166 |
while the "decode" method expects to be handled an UTF-8-encoded |
| 167 |
string. Please note that UTF-8-encoded strings do not contain any |
| 168 |
characters outside the range 0..255, they are thus useful for |
| 169 |
bytewise/binary I/O. In future versions, enabling this option might |
| 170 |
enable autodetection of the UTF-16 and UTF-32 encoding families, as |
| 171 |
described in RFC4627. |
| 172 |
|
| 173 |
If $enable is false, then the "encode" method will return the JSON |
| 174 |
string as a (non-encoded) unicode string, while "decode" expects |
| 175 |
thus a unicode string. Any decoding or encoding (e.g. to UTF-8 or |
| 176 |
UTF-16) needs to be done yourself, e.g. using the Encode module. |
| 177 |
|
| 178 |
Example, output UTF-16BE-encoded JSON: |
| 179 |
|
| 180 |
use Encode; |
| 181 |
$jsontext = encode "UTF-16BE", JSON::XS->new->encode ($object); |
| 182 |
|
| 183 |
Example, decode UTF-32LE-encoded JSON: |
| 184 |
|
| 185 |
use Encode; |
| 186 |
$object = JSON::XS->new->decode (decode "UTF-32LE", $jsontext); |
| 187 |
|
| 188 |
$json = $json->pretty ([$enable]) |
| 189 |
This enables (or disables) all of the "indent", "space_before" and |
| 190 |
"space_after" (and in the future possibly more) flags in one call to |
| 191 |
generate the most readable (or most compact) form possible. |
| 192 |
|
| 193 |
Example, pretty-print some simple structure: |
| 194 |
|
| 195 |
my $json = JSON::XS->new->pretty(1)->encode ({a => [1,2]}) |
| 196 |
=> |
| 197 |
{ |
| 198 |
"a" : [ |
| 199 |
1, |
| 200 |
2 |
| 201 |
] |
| 202 |
} |
| 203 |
|
| 204 |
$json = $json->indent ([$enable]) |
| 205 |
If $enable is true (or missing), then the "encode" method will use a |
| 206 |
multiline format as output, putting every array member or |
| 207 |
object/hash key-value pair into its own line, identing them |
| 208 |
properly. |
| 209 |
|
| 210 |
If $enable is false, no newlines or indenting will be produced, and |
| 211 |
the resulting JSON text is guarenteed not to contain any "newlines". |
| 212 |
|
| 213 |
This setting has no effect when decoding JSON texts. |
| 214 |
|
| 215 |
$json = $json->space_before ([$enable]) |
| 216 |
If $enable is true (or missing), then the "encode" method will add |
| 217 |
an extra optional space before the ":" separating keys from values |
| 218 |
in JSON objects. |
| 219 |
|
| 220 |
If $enable is false, then the "encode" method will not add any extra |
| 221 |
space at those places. |
| 222 |
|
| 223 |
This setting has no effect when decoding JSON texts. You will also |
| 224 |
most likely combine this setting with "space_after". |
| 225 |
|
| 226 |
Example, space_before enabled, space_after and indent disabled: |
| 227 |
|
| 228 |
{"key" :"value"} |
| 229 |
|
| 230 |
$json = $json->space_after ([$enable]) |
| 231 |
If $enable is true (or missing), then the "encode" method will add |
| 232 |
an extra optional space after the ":" separating keys from values in |
| 233 |
JSON objects and extra whitespace after the "," separating key-value |
| 234 |
pairs and array members. |
| 235 |
|
| 236 |
If $enable is false, then the "encode" method will not add any extra |
| 237 |
space at those places. |
| 238 |
|
| 239 |
This setting has no effect when decoding JSON texts. |
| 240 |
|
| 241 |
Example, space_before and indent disabled, space_after enabled: |
| 242 |
|
| 243 |
{"key": "value"} |
| 244 |
|
| 245 |
$json = $json->relaxed ([$enable]) |
| 246 |
If $enable is true (or missing), then "decode" will accept some |
| 247 |
extensions to normal JSON syntax (see below). "encode" will not be |
| 248 |
affected in anyway. *Be aware that this option makes you accept |
| 249 |
invalid JSON texts as if they were valid!*. I suggest only to use |
| 250 |
this option to parse application-specific files written by humans |
| 251 |
(configuration files, resource files etc.) |
| 252 |
|
| 253 |
If $enable is false (the default), then "decode" will only accept |
| 254 |
valid JSON texts. |
| 255 |
|
| 256 |
Currently accepted extensions are: |
| 257 |
|
| 258 |
* list items can have an end-comma |
| 259 |
JSON *separates* array elements and key-value pairs with commas. |
| 260 |
This can be annoying if you write JSON texts manually and want |
| 261 |
to be able to quickly append elements, so this extension accepts |
| 262 |
comma at the end of such items not just between them: |
| 263 |
|
| 264 |
[ |
| 265 |
1, |
| 266 |
2, <- this comma not normally allowed |
| 267 |
] |
| 268 |
{ |
| 269 |
"k1": "v1", |
| 270 |
"k2": "v2", <- this comma not normally allowed |
| 271 |
} |
| 272 |
|
| 273 |
$json = $json->canonical ([$enable]) |
| 274 |
If $enable is true (or missing), then the "encode" method will |
| 275 |
output JSON objects by sorting their keys. This is adding a |
| 276 |
comparatively high overhead. |
| 277 |
|
| 278 |
If $enable is false, then the "encode" method will output key-value |
| 279 |
pairs in the order Perl stores them (which will likely change |
| 280 |
between runs of the same script). |
| 281 |
|
| 282 |
This option is useful if you want the same data structure to be |
| 283 |
encoded as the same JSON text (given the same overall settings). If |
| 284 |
it is disabled, the same hash migh be encoded differently even if |
| 285 |
contains the same data, as key-value pairs have no inherent ordering |
| 286 |
in Perl. |
| 287 |
|
| 288 |
This setting has no effect when decoding JSON texts. |
| 289 |
|
| 290 |
$json = $json->allow_nonref ([$enable]) |
| 291 |
If $enable is true (or missing), then the "encode" method can |
| 292 |
convert a non-reference into its corresponding string, number or |
| 293 |
null JSON value, which is an extension to RFC4627. Likewise, |
| 294 |
"decode" will accept those JSON values instead of croaking. |
| 295 |
|
| 296 |
If $enable is false, then the "encode" method will croak if it isn't |
| 297 |
passed an arrayref or hashref, as JSON texts must either be an |
| 298 |
object or array. Likewise, "decode" will croak if given something |
| 299 |
that is not a JSON object or array. |
| 300 |
|
| 301 |
Example, encode a Perl scalar as JSON value with enabled |
| 302 |
"allow_nonref", resulting in an invalid JSON text: |
| 303 |
|
| 304 |
JSON::XS->new->allow_nonref->encode ("Hello, World!") |
| 305 |
=> "Hello, World!" |
| 306 |
|
| 307 |
$json = $json->allow_blessed ([$enable]) |
| 308 |
If $enable is true (or missing), then the "encode" method will not |
| 309 |
barf when it encounters a blessed reference. Instead, the value of |
| 310 |
the convert_blessed option will decide wether "null" |
| 311 |
("convert_blessed" disabled or no "to_json" method found) or a |
| 312 |
representation of the object ("convert_blessed" enabled and |
| 313 |
"to_json" method found) is being encoded. Has no effect on "decode". |
| 314 |
|
| 315 |
If $enable is false (the default), then "encode" will throw an |
| 316 |
exception when it encounters a blessed object. |
| 317 |
|
| 318 |
$json = $json->convert_blessed ([$enable]) |
| 319 |
If $enable is true (or missing), then "encode", upon encountering a |
| 320 |
blessed object, will check for the availability of the "TO_JSON" |
| 321 |
method on the object's class. If found, it will be called in scalar |
| 322 |
context and the resulting scalar will be encoded instead of the |
| 323 |
object. If no "TO_JSON" method is found, the value of |
| 324 |
"allow_blessed" will decide what to do. |
| 325 |
|
| 326 |
The "TO_JSON" method may safely call die if it wants. If "TO_JSON" |
| 327 |
returns other blessed objects, those will be handled in the same |
| 328 |
way. "TO_JSON" must take care of not causing an endless recursion |
| 329 |
cycle (== crash) in this case. The name of "TO_JSON" was chosen |
| 330 |
because other methods called by the Perl core (== not by the user of |
| 331 |
the object) are usually in upper case letters and to avoid |
| 332 |
collisions with the "to_json" function. |
| 333 |
|
| 334 |
This setting does not yet influence "decode" in any way, but in the |
| 335 |
future, global hooks might get installed that influence "decode" and |
| 336 |
are enabled by this setting. |
| 337 |
|
| 338 |
If $enable is false, then the "allow_blessed" setting will decide |
| 339 |
what to do when a blessed object is found. |
| 340 |
|
| 341 |
$json = $json->filter_json_object ([$coderef->($hashref)]) |
| 342 |
When $coderef is specified, it will be called from "decode" each |
| 343 |
time it decodes a JSON object. The only argument is a reference to |
| 344 |
the newly-created hash. If the code references returns a single |
| 345 |
scalar (which need not be a reference), this value (i.e. a copy of |
| 346 |
that scalar to avoid aliasing) is inserted into the deserialised |
| 347 |
data structure. If it returns an empty list (NOTE: *not* "undef", |
| 348 |
which is a valid scalar), the original deserialised hash will be |
| 349 |
inserted. This setting can slow down decoding considerably. |
| 350 |
|
| 351 |
When $coderef is omitted or undefined, any existing callback will be |
| 352 |
removed and "decode" will not change the deserialised hash in any |
| 353 |
way. |
| 354 |
|
| 355 |
Example, convert all JSON objects into the integer 5: |
| 356 |
|
| 357 |
my $js = JSON::XS->new->filter_json_object (sub { 5 }); |
| 358 |
# returns [5] |
| 359 |
$js->decode ('[{}]') |
| 360 |
# throw an exception because allow_nonref is not enabled |
| 361 |
# so a lone 5 is not allowed. |
| 362 |
$js->decode ('{"a":1, "b":2}'); |
| 363 |
|
| 364 |
$json = $json->filter_json_single_key_object ($key [=> |
| 365 |
$coderef->($value)]) |
| 366 |
Works remotely similar to "filter_json_object", but is only called |
| 367 |
for JSON objects having a single key named $key. |
| 368 |
|
| 369 |
This $coderef is called before the one specified via |
| 370 |
"filter_json_object", if any. It gets passed the single value in the |
| 371 |
JSON object. If it returns a single value, it will be inserted into |
| 372 |
the data structure. If it returns nothing (not even "undef" but the |
| 373 |
empty list), the callback from "filter_json_object" will be called |
| 374 |
next, as if no single-key callback were specified. |
| 375 |
|
| 376 |
If $coderef is omitted or undefined, the corresponding callback will |
| 377 |
be disabled. There can only ever be one callback for a given key. |
| 378 |
|
| 379 |
As this callback gets called less often then the |
| 380 |
"filter_json_object" one, decoding speed will not usually suffer as |
| 381 |
much. Therefore, single-key objects make excellent targets to |
| 382 |
serialise Perl objects into, especially as single-key JSON objects |
| 383 |
are as close to the type-tagged value concept as JSON gets (its |
| 384 |
basically an ID/VALUE tuple). Of course, JSON does not support this |
| 385 |
in any way, so you need to make sure your data never looks like a |
| 386 |
serialised Perl hash. |
| 387 |
|
| 388 |
Typical names for the single object key are "__class_whatever__", or |
| 389 |
"$__dollars_are_rarely_used__$" or "}ugly_brace_placement", or even |
| 390 |
things like "__class_md5sum(classname)__", to reduce the risk of |
| 391 |
clashing with real hashes. |
| 392 |
|
| 393 |
Example, decode JSON objects of the form "{ "__widget__" => <id> }" |
| 394 |
into the corresponding $WIDGET{<id>} object: |
| 395 |
|
| 396 |
# return whatever is in $WIDGET{5}: |
| 397 |
JSON::XS |
| 398 |
->new |
| 399 |
->filter_json_single_key_object (__widget__ => sub { |
| 400 |
$WIDGET{ $_[0] } |
| 401 |
}) |
| 402 |
->decode ('{"__widget__": 5') |
| 403 |
|
| 404 |
# this can be used with a TO_JSON method in some "widget" class |
| 405 |
# for serialisation to json: |
| 406 |
sub WidgetBase::TO_JSON { |
| 407 |
my ($self) = @_; |
| 408 |
|
| 409 |
unless ($self->{id}) { |
| 410 |
$self->{id} = ..get..some..id..; |
| 411 |
$WIDGET{$self->{id}} = $self; |
| 412 |
} |
| 413 |
|
| 414 |
{ __widget__ => $self->{id} } |
| 415 |
} |
| 416 |
|
| 417 |
$json = $json->shrink ([$enable]) |
| 418 |
Perl usually over-allocates memory a bit when allocating space for |
| 419 |
strings. This flag optionally resizes strings generated by either |
| 420 |
"encode" or "decode" to their minimum size possible. This can save |
| 421 |
memory when your JSON texts are either very very long or you have |
| 422 |
many short strings. It will also try to downgrade any strings to |
| 423 |
octet-form if possible: perl stores strings internally either in an |
| 424 |
encoding called UTF-X or in octet-form. The latter cannot store |
| 425 |
everything but uses less space in general (and some buggy Perl or C |
| 426 |
code might even rely on that internal representation being used). |
| 427 |
|
| 428 |
The actual definition of what shrink does might change in future |
| 429 |
versions, but it will always try to save space at the expense of |
| 430 |
time. |
| 431 |
|
| 432 |
If $enable is true (or missing), the string returned by "encode" |
| 433 |
will be shrunk-to-fit, while all strings generated by "decode" will |
| 434 |
also be shrunk-to-fit. |
| 435 |
|
| 436 |
If $enable is false, then the normal perl allocation algorithms are |
| 437 |
used. If you work with your data, then this is likely to be faster. |
| 438 |
|
| 439 |
In the future, this setting might control other things, such as |
| 440 |
converting strings that look like integers or floats into integers |
| 441 |
or floats internally (there is no difference on the Perl level), |
| 442 |
saving space. |
| 443 |
|
| 444 |
$json = $json->max_depth ([$maximum_nesting_depth]) |
| 445 |
Sets the maximum nesting level (default 512) accepted while encoding |
| 446 |
or decoding. If the JSON text or Perl data structure has an equal or |
| 447 |
higher nesting level then this limit, then the encoder and decoder |
| 448 |
will stop and croak at that point. |
| 449 |
|
| 450 |
Nesting level is defined by number of hash- or arrayrefs that the |
| 451 |
encoder needs to traverse to reach a given point or the number of |
| 452 |
"{" or "[" characters without their matching closing parenthesis |
| 453 |
crossed to reach a given character in a string. |
| 454 |
|
| 455 |
Setting the maximum depth to one disallows any nesting, so that |
| 456 |
ensures that the object is only a single hash/object or array. |
| 457 |
|
| 458 |
The argument to "max_depth" will be rounded up to the next highest |
| 459 |
power of two. If no argument is given, the highest possible setting |
| 460 |
will be used, which is rarely useful. |
| 461 |
|
| 462 |
See SECURITY CONSIDERATIONS, below, for more info on why this is |
| 463 |
useful. |
| 464 |
|
| 465 |
$json = $json->max_size ([$maximum_string_size]) |
| 466 |
Set the maximum length a JSON text may have (in bytes) where |
| 467 |
decoding is being attempted. The default is 0, meaning no limit. |
| 468 |
When "decode" is called on a string longer then this number of |
| 469 |
characters it will not attempt to decode the string but throw an |
| 470 |
exception. This setting has no effect on "encode" (yet). |
| 471 |
|
| 472 |
The argument to "max_size" will be rounded up to the next highest |
| 473 |
power of two (so may be more than requested). If no argument is |
| 474 |
given, the limit check will be deactivated (same as when 0 is |
| 475 |
specified). |
| 476 |
|
| 477 |
See SECURITY CONSIDERATIONS, below, for more info on why this is |
| 478 |
useful. |
| 479 |
|
| 480 |
$json_text = $json->encode ($perl_scalar) |
| 481 |
Converts the given Perl data structure (a simple scalar or a |
| 482 |
reference to a hash or array) to its JSON representation. Simple |
| 483 |
scalars will be converted into JSON string or number sequences, |
| 484 |
while references to arrays become JSON arrays and references to |
| 485 |
hashes become JSON objects. Undefined Perl values (e.g. "undef") |
| 486 |
become JSON "null" values. Neither "true" nor "false" values will be |
| 487 |
generated. |
| 488 |
|
| 489 |
$perl_scalar = $json->decode ($json_text) |
| 490 |
The opposite of "encode": expects a JSON text and tries to parse it, |
| 491 |
returning the resulting simple scalar or reference. Croaks on error. |
| 492 |
|
| 493 |
JSON numbers and strings become simple Perl scalars. JSON arrays |
| 494 |
become Perl arrayrefs and JSON objects become Perl hashrefs. "true" |
| 495 |
becomes 1, "false" becomes 0 and "null" becomes "undef". |
| 496 |
|
| 497 |
($perl_scalar, $characters) = $json->decode_prefix ($json_text) |
| 498 |
This works like the "decode" method, but instead of raising an |
| 499 |
exception when there is trailing garbage after the first JSON |
| 500 |
object, it will silently stop parsing there and return the number of |
| 501 |
characters consumed so far. |
| 502 |
|
| 503 |
This is useful if your JSON texts are not delimited by an outer |
| 504 |
protocol (which is not the brightest thing to do in the first place) |
| 505 |
and you need to know where the JSON text ends. |
| 506 |
|
| 507 |
JSON::XS->new->decode_prefix ("[1] the tail") |
| 508 |
=> ([], 3) |
| 509 |
|
| 510 |
MAPPING |
| 511 |
This section describes how JSON::XS maps Perl values to JSON values and |
| 512 |
vice versa. These mappings are designed to "do the right thing" in most |
| 513 |
circumstances automatically, preserving round-tripping characteristics |
| 514 |
(what you put in comes out as something equivalent). |
| 515 |
|
| 516 |
For the more enlightened: note that in the following descriptions, |
| 517 |
lowercase *perl* refers to the Perl interpreter, while uppcercase *Perl* |
| 518 |
refers to the abstract Perl language itself. |
| 519 |
|
| 520 |
JSON -> PERL |
| 521 |
object |
| 522 |
A JSON object becomes a reference to a hash in Perl. No ordering of |
| 523 |
object keys is preserved (JSON does not preserver object key |
| 524 |
ordering itself). |
| 525 |
|
| 526 |
array |
| 527 |
A JSON array becomes a reference to an array in Perl. |
| 528 |
|
| 529 |
string |
| 530 |
A JSON string becomes a string scalar in Perl - Unicode codepoints |
| 531 |
in JSON are represented by the same codepoints in the Perl string, |
| 532 |
so no manual decoding is necessary. |
| 533 |
|
| 534 |
number |
| 535 |
A JSON number becomes either an integer, numeric (floating point) or |
| 536 |
string scalar in perl, depending on its range and any fractional |
| 537 |
parts. On the Perl level, there is no difference between those as |
| 538 |
Perl handles all the conversion details, but an integer may take |
| 539 |
slightly less memory and might represent more values exactly than |
| 540 |
(floating point) numbers. |
| 541 |
|
| 542 |
If the number consists of digits only, JSON::XS will try to |
| 543 |
represent it as an integer value. If that fails, it will try to |
| 544 |
represent it as a numeric (floating point) value if that is possible |
| 545 |
without loss of precision. Otherwise it will preserve the number as |
| 546 |
a string value. |
| 547 |
|
| 548 |
Numbers containing a fractional or exponential part will always be |
| 549 |
represented as numeric (floating point) values, possibly at a loss |
| 550 |
of precision. |
| 551 |
|
| 552 |
This might create round-tripping problems as numbers might become |
| 553 |
strings, but as Perl is typeless there is no other way to do it. |
| 554 |
|
| 555 |
true, false |
| 556 |
These JSON atoms become "JSON::XS::true" and "JSON::XS::false", |
| 557 |
respectively. They are overloaded to act almost exactly like the |
| 558 |
numbers 1 and 0. You can check wether a scalar is a JSON boolean by |
| 559 |
using the "JSON::XS::is_bool" function. |
| 560 |
|
| 561 |
null |
| 562 |
A JSON null atom becomes "undef" in Perl. |
| 563 |
|
| 564 |
PERL -> JSON |
| 565 |
The mapping from Perl to JSON is slightly more difficult, as Perl is a |
| 566 |
truly typeless language, so we can only guess which JSON type is meant |
| 567 |
by a Perl value. |
| 568 |
|
| 569 |
hash references |
| 570 |
Perl hash references become JSON objects. As there is no inherent |
| 571 |
ordering in hash keys (or JSON objects), they will usually be |
| 572 |
encoded in a pseudo-random order that can change between runs of the |
| 573 |
same program but stays generally the same within a single run of a |
| 574 |
program. JSON::XS can optionally sort the hash keys (determined by |
| 575 |
the *canonical* flag), so the same datastructure will serialise to |
| 576 |
the same JSON text (given same settings and version of JSON::XS), |
| 577 |
but this incurs a runtime overhead and is only rarely useful, e.g. |
| 578 |
when you want to compare some JSON text against another for |
| 579 |
equality. |
| 580 |
|
| 581 |
array references |
| 582 |
Perl array references become JSON arrays. |
| 583 |
|
| 584 |
other references |
| 585 |
Other unblessed references are generally not allowed and will cause |
| 586 |
an exception to be thrown, except for references to the integers 0 |
| 587 |
and 1, which get turned into "false" and "true" atoms in JSON. You |
| 588 |
can also use "JSON::XS::false" and "JSON::XS::true" to improve |
| 589 |
readability. |
| 590 |
|
| 591 |
to_json [\0,JSON::XS::true] # yields [false,true] |
| 592 |
|
| 593 |
JSON::XS::true, JSON::XS::false |
| 594 |
These special values become JSON true and JSON false values, |
| 595 |
respectively. You cna alos use "\1" and "\0" directly if you want. |
| 596 |
|
| 597 |
blessed objects |
| 598 |
Blessed objects are not allowed. JSON::XS currently tries to encode |
| 599 |
their underlying representation (hash- or arrayref), but this |
| 600 |
behaviour might change in future versions. |
| 601 |
|
| 602 |
simple scalars |
| 603 |
Simple Perl scalars (any scalar that is not a reference) are the |
| 604 |
most difficult objects to encode: JSON::XS will encode undefined |
| 605 |
scalars as JSON null value, scalars that have last been used in a |
| 606 |
string context before encoding as JSON strings and anything else as |
| 607 |
number value: |
| 608 |
|
| 609 |
# dump as number |
| 610 |
to_json [2] # yields [2] |
| 611 |
to_json [-3.0e17] # yields [-3e+17] |
| 612 |
my $value = 5; to_json [$value] # yields [5] |
| 613 |
|
| 614 |
# used as string, so dump as string |
| 615 |
print $value; |
| 616 |
to_json [$value] # yields ["5"] |
| 617 |
|
| 618 |
# undef becomes null |
| 619 |
to_json [undef] # yields [null] |
| 620 |
|
| 621 |
You can force the type to be a string by stringifying it: |
| 622 |
|
| 623 |
my $x = 3.1; # some variable containing a number |
| 624 |
"$x"; # stringified |
| 625 |
$x .= ""; # another, more awkward way to stringify |
| 626 |
print $x; # perl does it for you, too, quite often |
| 627 |
|
| 628 |
You can force the type to be a number by numifying it: |
| 629 |
|
| 630 |
my $x = "3"; # some variable containing a string |
| 631 |
$x += 0; # numify it, ensuring it will be dumped as a number |
| 632 |
$x *= 1; # same thing, the choise is yours. |
| 633 |
|
| 634 |
You can not currently output JSON booleans or force the type in |
| 635 |
other, less obscure, ways. Tell me if you need this capability. |
| 636 |
|
| 637 |
COMPARISON |
| 638 |
As already mentioned, this module was created because none of the |
| 639 |
existing JSON modules could be made to work correctly. First I will |
| 640 |
describe the problems (or pleasures) I encountered with various existing |
| 641 |
JSON modules, followed by some benchmark values. JSON::XS was designed |
| 642 |
not to suffer from any of these problems or limitations. |
| 643 |
|
| 644 |
JSON 1.07 |
| 645 |
Slow (but very portable, as it is written in pure Perl). |
| 646 |
|
| 647 |
Undocumented/buggy Unicode handling (how JSON handles unicode values |
| 648 |
is undocumented. One can get far by feeding it unicode strings and |
| 649 |
doing en-/decoding oneself, but unicode escapes are not working |
| 650 |
properly). |
| 651 |
|
| 652 |
No roundtripping (strings get clobbered if they look like numbers, |
| 653 |
e.g. the string 2.0 will encode to 2.0 instead of "2.0", and that |
| 654 |
will decode into the number 2. |
| 655 |
|
| 656 |
JSON::PC 0.01 |
| 657 |
Very fast. |
| 658 |
|
| 659 |
Undocumented/buggy Unicode handling. |
| 660 |
|
| 661 |
No roundtripping. |
| 662 |
|
| 663 |
Has problems handling many Perl values (e.g. regex results and other |
| 664 |
magic values will make it croak). |
| 665 |
|
| 666 |
Does not even generate valid JSON ("{1,2}" gets converted to "{1:2}" |
| 667 |
which is not a valid JSON text. |
| 668 |
|
| 669 |
Unmaintained (maintainer unresponsive for many months, bugs are not |
| 670 |
getting fixed). |
| 671 |
|
| 672 |
JSON::Syck 0.21 |
| 673 |
Very buggy (often crashes). |
| 674 |
|
| 675 |
Very inflexible (no human-readable format supported, format pretty |
| 676 |
much undocumented. I need at least a format for easy reading by |
| 677 |
humans and a single-line compact format for use in a protocol, and |
| 678 |
preferably a way to generate ASCII-only JSON texts). |
| 679 |
|
| 680 |
Completely broken (and confusingly documented) Unicode handling |
| 681 |
(unicode escapes are not working properly, you need to set |
| 682 |
ImplicitUnicode to *different* values on en- and decoding to get |
| 683 |
symmetric behaviour). |
| 684 |
|
| 685 |
No roundtripping (simple cases work, but this depends on wether the |
| 686 |
scalar value was used in a numeric context or not). |
| 687 |
|
| 688 |
Dumping hashes may skip hash values depending on iterator state. |
| 689 |
|
| 690 |
Unmaintained (maintainer unresponsive for many months, bugs are not |
| 691 |
getting fixed). |
| 692 |
|
| 693 |
Does not check input for validity (i.e. will accept non-JSON input |
| 694 |
and return "something" instead of raising an exception. This is a |
| 695 |
security issue: imagine two banks transfering money between each |
| 696 |
other using JSON. One bank might parse a given non-JSON request and |
| 697 |
deduct money, while the other might reject the transaction with a |
| 698 |
syntax error. While a good protocol will at least recover, that is |
| 699 |
extra unnecessary work and the transaction will still not succeed). |
| 700 |
|
| 701 |
JSON::DWIW 0.04 |
| 702 |
Very fast. Very natural. Very nice. |
| 703 |
|
| 704 |
Undocumented unicode handling (but the best of the pack. Unicode |
| 705 |
escapes still don't get parsed properly). |
| 706 |
|
| 707 |
Very inflexible. |
| 708 |
|
| 709 |
No roundtripping. |
| 710 |
|
| 711 |
Does not generate valid JSON texts (key strings are often unquoted, |
| 712 |
empty keys result in nothing being output) |
| 713 |
|
| 714 |
Does not check input for validity. |
| 715 |
|
| 716 |
JSON and YAML |
| 717 |
You often hear that JSON is a subset (or a close subset) of YAML. This |
| 718 |
is, however, a mass hysteria and very far from the truth. In general, |
| 719 |
there is no way to configure JSON::XS to output a data structure as |
| 720 |
valid YAML. |
| 721 |
|
| 722 |
If you really must use JSON::XS to generate YAML, you should use this |
| 723 |
algorithm (subject to change in future versions): |
| 724 |
|
| 725 |
my $to_yaml = JSON::XS->new->utf8->space_after (1); |
| 726 |
my $yaml = $to_yaml->encode ($ref) . "\n"; |
| 727 |
|
| 728 |
This will usually generate JSON texts that also parse as valid YAML. |
| 729 |
Please note that YAML has hardcoded limits on (simple) object key |
| 730 |
lengths that JSON doesn't have, so you should make sure that your hash |
| 731 |
keys are noticably shorter than the 1024 characters YAML allows. |
| 732 |
|
| 733 |
There might be other incompatibilities that I am not aware of. In |
| 734 |
general you should not try to generate YAML with a JSON generator or |
| 735 |
vice versa, or try to parse JSON with a YAML parser or vice versa: |
| 736 |
chances are high that you will run into severe interoperability |
| 737 |
problems. |
| 738 |
|
| 739 |
SPEED |
| 740 |
It seems that JSON::XS is surprisingly fast, as shown in the following |
| 741 |
tables. They have been generated with the help of the "eg/bench" program |
| 742 |
in the JSON::XS distribution, to make it easy to compare on your own |
| 743 |
system. |
| 744 |
|
| 745 |
First comes a comparison between various modules using a very short |
| 746 |
single-line JSON string: |
| 747 |
|
| 748 |
{"method": "handleMessage", "params": ["user1", "we were just talking"], \ |
| 749 |
"id": null, "array":[1,11,234,-5,1e5,1e7, true, false]} |
| 750 |
|
| 751 |
It shows the number of encodes/decodes per second (JSON::XS uses the |
| 752 |
functional interface, while JSON::XS/2 uses the OO interface with |
| 753 |
pretty-printing and hashkey sorting enabled, JSON::XS/3 enables shrink). |
| 754 |
Higher is better: |
| 755 |
|
| 756 |
Storable | 15779.925 | 14169.946 | |
| 757 |
-----------+------------+------------+ |
| 758 |
module | encode | decode | |
| 759 |
-----------|------------|------------| |
| 760 |
JSON | 4990.842 | 4088.813 | |
| 761 |
JSON::DWIW | 51653.990 | 71575.154 | |
| 762 |
JSON::PC | 65948.176 | 74631.744 | |
| 763 |
JSON::PP | 8931.652 | 3817.168 | |
| 764 |
JSON::Syck | 24877.248 | 27776.848 | |
| 765 |
JSON::XS | 388361.481 | 227951.304 | |
| 766 |
JSON::XS/2 | 227951.304 | 218453.333 | |
| 767 |
JSON::XS/3 | 338250.323 | 218453.333 | |
| 768 |
Storable | 16500.016 | 135300.129 | |
| 769 |
-----------+------------+------------+ |
| 770 |
|
| 771 |
That is, JSON::XS is about five times faster than JSON::DWIW on |
| 772 |
encoding, about three times faster on decoding, and over fourty times |
| 773 |
faster than JSON, even with pretty-printing and key sorting. It also |
| 774 |
compares favourably to Storable for small amounts of data. |
| 775 |
|
| 776 |
Using a longer test string (roughly 18KB, generated from Yahoo! Locals |
| 777 |
search API (http://nanoref.com/yahooapis/mgPdGg): |
| 778 |
|
| 779 |
module | encode | decode | |
| 780 |
-----------|------------|------------| |
| 781 |
JSON | 55.260 | 34.971 | |
| 782 |
JSON::DWIW | 825.228 | 1082.513 | |
| 783 |
JSON::PC | 3571.444 | 2394.829 | |
| 784 |
JSON::PP | 210.987 | 32.574 | |
| 785 |
JSON::Syck | 552.551 | 787.544 | |
| 786 |
JSON::XS | 5780.463 | 4854.519 | |
| 787 |
JSON::XS/2 | 3869.998 | 4798.975 | |
| 788 |
JSON::XS/3 | 5862.880 | 4798.975 | |
| 789 |
Storable | 4445.002 | 5235.027 | |
| 790 |
-----------+------------+------------+ |
| 791 |
|
| 792 |
Again, JSON::XS leads by far (except for Storable which non-surprisingly |
| 793 |
decodes faster). |
| 794 |
|
| 795 |
On large strings containing lots of high unicode characters, some |
| 796 |
modules (such as JSON::PC) seem to decode faster than JSON::XS, but the |
| 797 |
result will be broken due to missing (or wrong) unicode handling. Others |
| 798 |
refuse to decode or encode properly, so it was impossible to prepare a |
| 799 |
fair comparison table for that case. |
| 800 |
|
| 801 |
SECURITY CONSIDERATIONS |
| 802 |
When you are using JSON in a protocol, talking to untrusted potentially |
| 803 |
hostile creatures requires relatively few measures. |
| 804 |
|
| 805 |
First of all, your JSON decoder should be secure, that is, should not |
| 806 |
have any buffer overflows. Obviously, this module should ensure that and |
| 807 |
I am trying hard on making that true, but you never know. |
| 808 |
|
| 809 |
Second, you need to avoid resource-starving attacks. That means you |
| 810 |
should limit the size of JSON texts you accept, or make sure then when |
| 811 |
your resources run out, thats just fine (e.g. by using a separate |
| 812 |
process that can crash safely). The size of a JSON text in octets or |
| 813 |
characters is usually a good indication of the size of the resources |
| 814 |
required to decode it into a Perl structure. While JSON::XS can check |
| 815 |
the size of the JSON text, it might be too late when you already have it |
| 816 |
in memory, so you might want to check the size before you accept the |
| 817 |
string. |
| 818 |
|
| 819 |
Third, JSON::XS recurses using the C stack when decoding objects and |
| 820 |
arrays. The C stack is a limited resource: for instance, on my amd64 |
| 821 |
machine with 8MB of stack size I can decode around 180k nested arrays |
| 822 |
but only 14k nested JSON objects (due to perl itself recursing deeply on |
| 823 |
croak to free the temporary). If that is exceeded, the program crashes. |
| 824 |
to be conservative, the default nesting limit is set to 512. If your |
| 825 |
process has a smaller stack, you should adjust this setting accordingly |
| 826 |
with the "max_depth" method. |
| 827 |
|
| 828 |
And last but least, something else could bomb you that I forgot to think |
| 829 |
of. In that case, you get to keep the pieces. I am always open for |
| 830 |
hints, though... |
| 831 |
|
| 832 |
If you are using JSON::XS to return packets to consumption by javascript |
| 833 |
scripts in a browser you should have a look at |
| 834 |
<http://jpsykes.com/47/practical-csrf-and-json-security> to see wether |
| 835 |
you are vulnerable to some common attack vectors (which really are |
| 836 |
browser design bugs, but it is still you who will have to deal with it, |
| 837 |
as major browser developers care only for features, not about doing |
| 838 |
security right). |
| 839 |
|
| 840 |
BUGS |
| 841 |
While the goal of this module is to be correct, that unfortunately does |
| 842 |
not mean its bug-free, only that I think its design is bug-free. It is |
| 843 |
still relatively early in its development. If you keep reporting bugs |
| 844 |
they will be fixed swiftly, though. |
| 845 |
|
| 846 |
AUTHOR |
| 847 |
Marc Lehmann <schmorp@schmorp.de> |
| 848 |
http://home.schmorp.de/ |
| 849 |
|