1 |
NAME |
2 |
JSON::XS - JSON serialising/deserialising, done correctly and fast |
3 |
|
4 |
SYNOPSIS |
5 |
use JSON::XS; |
6 |
|
7 |
# exported functions, croak on error |
8 |
|
9 |
$utf8_encoded_json_text = to_json $perl_hash_or_arrayref; |
10 |
$perl_hash_or_arrayref = from_json $utf8_encoded_json_text; |
11 |
|
12 |
# oo-interface |
13 |
|
14 |
$coder = JSON::XS->new->ascii->pretty->allow_nonref; |
15 |
$pretty_printed_unencoded = $coder->encode ($perl_scalar); |
16 |
$perl_scalar = $coder->decode ($unicode_json_text); |
17 |
|
18 |
DESCRIPTION |
19 |
This module converts Perl data structures to JSON and vice versa. Its |
20 |
primary goal is to be *correct* and its secondary goal is to be *fast*. |
21 |
To reach the latter goal it was written in C. |
22 |
|
23 |
As this is the n-th-something JSON module on CPAN, what was the reason |
24 |
to write yet another JSON module? While it seems there are many JSON |
25 |
modules, none of them correctly handle all corner cases, and in most |
26 |
cases their maintainers are unresponsive, gone missing, or not listening |
27 |
to bug reports for other reasons. |
28 |
|
29 |
See COMPARISON, below, for a comparison to some other JSON modules. |
30 |
|
31 |
See MAPPING, below, on how JSON::XS maps perl values to JSON values and |
32 |
vice versa. |
33 |
|
34 |
FEATURES |
35 |
* correct handling of unicode issues |
36 |
This module knows how to handle Unicode, and even documents how and |
37 |
when it does so. |
38 |
|
39 |
* round-trip integrity |
40 |
When you serialise a perl data structure using only datatypes |
41 |
supported by JSON, the deserialised data structure is identical on |
42 |
the Perl level. (e.g. the string "2.0" doesn't suddenly become "2"). |
43 |
|
44 |
* strict checking of JSON correctness |
45 |
There is no guessing, no generating of illegal JSON texts by |
46 |
default, and only JSON is accepted as input by default (the latter |
47 |
is a security feature). |
48 |
|
49 |
* fast |
50 |
Compared to other JSON modules, this module compares favourably in |
51 |
terms of speed, too. |
52 |
|
53 |
* simple to use |
54 |
This module has both a simple functional interface as well as an OO |
55 |
interface. |
56 |
|
57 |
* reasonably versatile output formats |
58 |
You can choose between the most compact guarenteed single-line |
59 |
format possible (nice for simple line-based protocols), a pure-ascii |
60 |
format (for when your transport is not 8-bit clean), or a |
61 |
pretty-printed format (for when you want to read that stuff). Or you |
62 |
can combine those features in whatever way you like. |
63 |
|
64 |
FUNCTIONAL INTERFACE |
65 |
The following convinience methods are provided by this module. They are |
66 |
exported by default: |
67 |
|
68 |
$json_text = to_json $perl_scalar |
69 |
Converts the given Perl data structure (a simple scalar or a |
70 |
reference to a hash or array) to a UTF-8 encoded, binary string |
71 |
(that is, the string contains octets only). Croaks on error. |
72 |
|
73 |
This function call is functionally identical to: |
74 |
|
75 |
$json_text = JSON::XS->new->utf8->encode ($perl_scalar) |
76 |
|
77 |
except being faster. |
78 |
|
79 |
$perl_scalar = from_json $json_text |
80 |
The opposite of "to_json": expects an UTF-8 (binary) string and |
81 |
tries to parse that as an UTF-8 encoded JSON text, returning the |
82 |
resulting simple scalar or reference. Croaks on error. |
83 |
|
84 |
This function call is functionally identical to: |
85 |
|
86 |
$perl_scalar = JSON::XS->new->utf8->decode ($json_text) |
87 |
|
88 |
except being faster. |
89 |
|
90 |
OBJECT-ORIENTED INTERFACE |
91 |
The object oriented interface lets you configure your own encoding or |
92 |
decoding style, within the limits of supported formats. |
93 |
|
94 |
$json = new JSON::XS |
95 |
Creates a new JSON::XS object that can be used to de/encode JSON |
96 |
strings. All boolean flags described below are by default |
97 |
*disabled*. |
98 |
|
99 |
The mutators for flags all return the JSON object again and thus |
100 |
calls can be chained: |
101 |
|
102 |
my $json = JSON::XS->new->utf8->space_after->encode ({a => [1,2]}) |
103 |
=> {"a": [1, 2]} |
104 |
|
105 |
$json = $json->ascii ([$enable]) |
106 |
If $enable is true (or missing), then the "encode" method will not |
107 |
generate characters outside the code range 0..127 (which is ASCII). |
108 |
Any unicode characters outside that range will be escaped using |
109 |
either a single \uXXXX (BMP characters) or a double \uHHHH\uLLLLL |
110 |
escape sequence, as per RFC4627. |
111 |
|
112 |
If $enable is false, then the "encode" method will not escape |
113 |
Unicode characters unless required by the JSON syntax. This results |
114 |
in a faster and more compact format. |
115 |
|
116 |
JSON::XS->new->ascii (1)->encode ([chr 0x10401]) |
117 |
=> ["\ud801\udc01"] |
118 |
|
119 |
$json = $json->utf8 ([$enable]) |
120 |
If $enable is true (or missing), then the "encode" method will |
121 |
encode the JSON result into UTF-8, as required by many protocols, |
122 |
while the "decode" method expects to be handled an UTF-8-encoded |
123 |
string. Please note that UTF-8-encoded strings do not contain any |
124 |
characters outside the range 0..255, they are thus useful for |
125 |
bytewise/binary I/O. In future versions, enabling this option might |
126 |
enable autodetection of the UTF-16 and UTF-32 encoding families, as |
127 |
described in RFC4627. |
128 |
|
129 |
If $enable is false, then the "encode" method will return the JSON |
130 |
string as a (non-encoded) unicode string, while "decode" expects |
131 |
thus a unicode string. Any decoding or encoding (e.g. to UTF-8 or |
132 |
UTF-16) needs to be done yourself, e.g. using the Encode module. |
133 |
|
134 |
Example, output UTF-16BE-encoded JSON: |
135 |
|
136 |
use Encode; |
137 |
$jsontext = encode "UTF-16BE", JSON::XS->new->encode ($object); |
138 |
|
139 |
Example, decode UTF-32LE-encoded JSON: |
140 |
|
141 |
use Encode; |
142 |
$object = JSON::XS->new->decode (decode "UTF-32LE", $jsontext); |
143 |
|
144 |
$json = $json->pretty ([$enable]) |
145 |
This enables (or disables) all of the "indent", "space_before" and |
146 |
"space_after" (and in the future possibly more) flags in one call to |
147 |
generate the most readable (or most compact) form possible. |
148 |
|
149 |
Example, pretty-print some simple structure: |
150 |
|
151 |
my $json = JSON::XS->new->pretty(1)->encode ({a => [1,2]}) |
152 |
=> |
153 |
{ |
154 |
"a" : [ |
155 |
1, |
156 |
2 |
157 |
] |
158 |
} |
159 |
|
160 |
$json = $json->indent ([$enable]) |
161 |
If $enable is true (or missing), then the "encode" method will use a |
162 |
multiline format as output, putting every array member or |
163 |
object/hash key-value pair into its own line, identing them |
164 |
properly. |
165 |
|
166 |
If $enable is false, no newlines or indenting will be produced, and |
167 |
the resulting JSON text is guarenteed not to contain any "newlines". |
168 |
|
169 |
This setting has no effect when decoding JSON texts. |
170 |
|
171 |
$json = $json->space_before ([$enable]) |
172 |
If $enable is true (or missing), then the "encode" method will add |
173 |
an extra optional space before the ":" separating keys from values |
174 |
in JSON objects. |
175 |
|
176 |
If $enable is false, then the "encode" method will not add any extra |
177 |
space at those places. |
178 |
|
179 |
This setting has no effect when decoding JSON texts. You will also |
180 |
most likely combine this setting with "space_after". |
181 |
|
182 |
Example, space_before enabled, space_after and indent disabled: |
183 |
|
184 |
{"key" :"value"} |
185 |
|
186 |
$json = $json->space_after ([$enable]) |
187 |
If $enable is true (or missing), then the "encode" method will add |
188 |
an extra optional space after the ":" separating keys from values in |
189 |
JSON objects and extra whitespace after the "," separating key-value |
190 |
pairs and array members. |
191 |
|
192 |
If $enable is false, then the "encode" method will not add any extra |
193 |
space at those places. |
194 |
|
195 |
This setting has no effect when decoding JSON texts. |
196 |
|
197 |
Example, space_before and indent disabled, space_after enabled: |
198 |
|
199 |
{"key": "value"} |
200 |
|
201 |
$json = $json->canonical ([$enable]) |
202 |
If $enable is true (or missing), then the "encode" method will |
203 |
output JSON objects by sorting their keys. This is adding a |
204 |
comparatively high overhead. |
205 |
|
206 |
If $enable is false, then the "encode" method will output key-value |
207 |
pairs in the order Perl stores them (which will likely change |
208 |
between runs of the same script). |
209 |
|
210 |
This option is useful if you want the same data structure to be |
211 |
encoded as the same JSON text (given the same overall settings). If |
212 |
it is disabled, the same hash migh be encoded differently even if |
213 |
contains the same data, as key-value pairs have no inherent ordering |
214 |
in Perl. |
215 |
|
216 |
This setting has no effect when decoding JSON texts. |
217 |
|
218 |
$json = $json->allow_nonref ([$enable]) |
219 |
If $enable is true (or missing), then the "encode" method can |
220 |
convert a non-reference into its corresponding string, number or |
221 |
null JSON value, which is an extension to RFC4627. Likewise, |
222 |
"decode" will accept those JSON values instead of croaking. |
223 |
|
224 |
If $enable is false, then the "encode" method will croak if it isn't |
225 |
passed an arrayref or hashref, as JSON texts must either be an |
226 |
object or array. Likewise, "decode" will croak if given something |
227 |
that is not a JSON object or array. |
228 |
|
229 |
Example, encode a Perl scalar as JSON value with enabled |
230 |
"allow_nonref", resulting in an invalid JSON text: |
231 |
|
232 |
JSON::XS->new->allow_nonref->encode ("Hello, World!") |
233 |
=> "Hello, World!" |
234 |
|
235 |
$json = $json->shrink ([$enable]) |
236 |
Perl usually over-allocates memory a bit when allocating space for |
237 |
strings. This flag optionally resizes strings generated by either |
238 |
"encode" or "decode" to their minimum size possible. This can save |
239 |
memory when your JSON texts are either very very long or you have |
240 |
many short strings. It will also try to downgrade any strings to |
241 |
octet-form if possible: perl stores strings internally either in an |
242 |
encoding called UTF-X or in octet-form. The latter cannot store |
243 |
everything but uses less space in general. |
244 |
|
245 |
If $enable is true (or missing), the string returned by "encode" |
246 |
will be shrunk-to-fit, while all strings generated by "decode" will |
247 |
also be shrunk-to-fit. |
248 |
|
249 |
If $enable is false, then the normal perl allocation algorithms are |
250 |
used. If you work with your data, then this is likely to be faster. |
251 |
|
252 |
In the future, this setting might control other things, such as |
253 |
converting strings that look like integers or floats into integers |
254 |
or floats internally (there is no difference on the Perl level), |
255 |
saving space. |
256 |
|
257 |
$json_text = $json->encode ($perl_scalar) |
258 |
Converts the given Perl data structure (a simple scalar or a |
259 |
reference to a hash or array) to its JSON representation. Simple |
260 |
scalars will be converted into JSON string or number sequences, |
261 |
while references to arrays become JSON arrays and references to |
262 |
hashes become JSON objects. Undefined Perl values (e.g. "undef") |
263 |
become JSON "null" values. Neither "true" nor "false" values will be |
264 |
generated. |
265 |
|
266 |
$perl_scalar = $json->decode ($json_text) |
267 |
The opposite of "encode": expects a JSON text and tries to parse it, |
268 |
returning the resulting simple scalar or reference. Croaks on error. |
269 |
|
270 |
JSON numbers and strings become simple Perl scalars. JSON arrays |
271 |
become Perl arrayrefs and JSON objects become Perl hashrefs. "true" |
272 |
becomes 1, "false" becomes 0 and "null" becomes "undef". |
273 |
|
274 |
MAPPING |
275 |
This section describes how JSON::XS maps Perl values to JSON values and |
276 |
vice versa. These mappings are designed to "do the right thing" in most |
277 |
circumstances automatically, preserving round-tripping characteristics |
278 |
(what you put in comes out as something equivalent). |
279 |
|
280 |
For the more enlightened: note that in the following descriptions, |
281 |
lowercase *perl* refers to the Perl interpreter, while uppcercase *Perl* |
282 |
refers to the abstract Perl language itself. |
283 |
|
284 |
JSON -> PERL |
285 |
object |
286 |
A JSON object becomes a reference to a hash in Perl. No ordering of |
287 |
object keys is preserved (JSON does not preserver object key |
288 |
ordering itself). |
289 |
|
290 |
array |
291 |
A JSON array becomes a reference to an array in Perl. |
292 |
|
293 |
string |
294 |
A JSON string becomes a string scalar in Perl - Unicode codepoints |
295 |
in JSON are represented by the same codepoints in the Perl string, |
296 |
so no manual decoding is necessary. |
297 |
|
298 |
number |
299 |
A JSON number becomes either an integer or numeric (floating point) |
300 |
scalar in perl, depending on its range and any fractional parts. On |
301 |
the Perl level, there is no difference between those as Perl handles |
302 |
all the conversion details, but an integer may take slightly less |
303 |
memory and might represent more values exactly than (floating point) |
304 |
numbers. |
305 |
|
306 |
true, false |
307 |
These JSON atoms become 0, 1, respectively. Information is lost in |
308 |
this process. Future versions might represent those values |
309 |
differently, but they will be guarenteed to act like these integers |
310 |
would normally in Perl. |
311 |
|
312 |
null |
313 |
A JSON null atom becomes "undef" in Perl. |
314 |
|
315 |
PERL -> JSON |
316 |
The mapping from Perl to JSON is slightly more difficult, as Perl is a |
317 |
truly typeless language, so we can only guess which JSON type is meant |
318 |
by a Perl value. |
319 |
|
320 |
hash references |
321 |
Perl hash references become JSON objects. As there is no inherent |
322 |
ordering in hash keys, they will usually be encoded in a |
323 |
pseudo-random order that can change between runs of the same program |
324 |
but stays generally the same within a single run of a program. |
325 |
JSON::XS can optionally sort the hash keys (determined by the |
326 |
*canonical* flag), so the same datastructure will serialise to the |
327 |
same JSON text (given same settings and version of JSON::XS), but |
328 |
this incurs a runtime overhead. |
329 |
|
330 |
array references |
331 |
Perl array references become JSON arrays. |
332 |
|
333 |
blessed objects |
334 |
Blessed objects are not allowed. JSON::XS currently tries to encode |
335 |
their underlying representation (hash- or arrayref), but this |
336 |
behaviour might change in future versions. |
337 |
|
338 |
simple scalars |
339 |
Simple Perl scalars (any scalar that is not a reference) are the |
340 |
most difficult objects to encode: JSON::XS will encode undefined |
341 |
scalars as JSON null value, scalars that have last been used in a |
342 |
string context before encoding as JSON strings and anything else as |
343 |
number value: |
344 |
|
345 |
# dump as number |
346 |
to_json [2] # yields [2] |
347 |
to_json [-3.0e17] # yields [-3e+17] |
348 |
my $value = 5; to_json [$value] # yields [5] |
349 |
|
350 |
# used as string, so dump as string |
351 |
print $value; |
352 |
to_json [$value] # yields ["5"] |
353 |
|
354 |
# undef becomes null |
355 |
to_json [undef] # yields [null] |
356 |
|
357 |
You can force the type to be a string by stringifying it: |
358 |
|
359 |
my $x = 3.1; # some variable containing a number |
360 |
"$x"; # stringified |
361 |
$x .= ""; # another, more awkward way to stringify |
362 |
print $x; # perl does it for you, too, quite often |
363 |
|
364 |
You can force the type to be a number by numifying it: |
365 |
|
366 |
my $x = "3"; # some variable containing a string |
367 |
$x += 0; # numify it, ensuring it will be dumped as a number |
368 |
$x *= 1; # same thing, the choise is yours. |
369 |
|
370 |
You can not currently output JSON booleans or force the type in |
371 |
other, less obscure, ways. Tell me if you need this capability. |
372 |
|
373 |
circular data structures |
374 |
Those will be encoded until memory or stackspace runs out. |
375 |
|
376 |
COMPARISON |
377 |
As already mentioned, this module was created because none of the |
378 |
existing JSON modules could be made to work correctly. First I will |
379 |
describe the problems (or pleasures) I encountered with various existing |
380 |
JSON modules, followed by some benchmark values. JSON::XS was designed |
381 |
not to suffer from any of these problems or limitations. |
382 |
|
383 |
JSON 1.07 |
384 |
Slow (but very portable, as it is written in pure Perl). |
385 |
|
386 |
Undocumented/buggy Unicode handling (how JSON handles unicode values |
387 |
is undocumented. One can get far by feeding it unicode strings and |
388 |
doing en-/decoding oneself, but unicode escapes are not working |
389 |
properly). |
390 |
|
391 |
No roundtripping (strings get clobbered if they look like numbers, |
392 |
e.g. the string 2.0 will encode to 2.0 instead of "2.0", and that |
393 |
will decode into the number 2. |
394 |
|
395 |
JSON::PC 0.01 |
396 |
Very fast. |
397 |
|
398 |
Undocumented/buggy Unicode handling. |
399 |
|
400 |
No roundtripping. |
401 |
|
402 |
Has problems handling many Perl values (e.g. regex results and other |
403 |
magic values will make it croak). |
404 |
|
405 |
Does not even generate valid JSON ("{1,2}" gets converted to "{1:2}" |
406 |
which is not a valid JSON text. |
407 |
|
408 |
Unmaintained (maintainer unresponsive for many months, bugs are not |
409 |
getting fixed). |
410 |
|
411 |
JSON::Syck 0.21 |
412 |
Very buggy (often crashes). |
413 |
|
414 |
Very inflexible (no human-readable format supported, format pretty |
415 |
much undocumented. I need at least a format for easy reading by |
416 |
humans and a single-line compact format for use in a protocol, and |
417 |
preferably a way to generate ASCII-only JSON texts). |
418 |
|
419 |
Completely broken (and confusingly documented) Unicode handling |
420 |
(unicode escapes are not working properly, you need to set |
421 |
ImplicitUnicode to *different* values on en- and decoding to get |
422 |
symmetric behaviour). |
423 |
|
424 |
No roundtripping (simple cases work, but this depends on wether the |
425 |
scalar value was used in a numeric context or not). |
426 |
|
427 |
Dumping hashes may skip hash values depending on iterator state. |
428 |
|
429 |
Unmaintained (maintainer unresponsive for many months, bugs are not |
430 |
getting fixed). |
431 |
|
432 |
Does not check input for validity (i.e. will accept non-JSON input |
433 |
and return "something" instead of raising an exception. This is a |
434 |
security issue: imagine two banks transfering money between each |
435 |
other using JSON. One bank might parse a given non-JSON request and |
436 |
deduct money, while the other might reject the transaction with a |
437 |
syntax error. While a good protocol will at least recover, that is |
438 |
extra unnecessary work and the transaction will still not succeed). |
439 |
|
440 |
JSON::DWIW 0.04 |
441 |
Very fast. Very natural. Very nice. |
442 |
|
443 |
Undocumented unicode handling (but the best of the pack. Unicode |
444 |
escapes still don't get parsed properly). |
445 |
|
446 |
Very inflexible. |
447 |
|
448 |
No roundtripping. |
449 |
|
450 |
Does not generate valid JSON texts (key strings are often unquoted, |
451 |
empty keys result in nothing being output) |
452 |
|
453 |
Does not check input for validity. |
454 |
|
455 |
SPEED |
456 |
It seems that JSON::XS is surprisingly fast, as shown in the following |
457 |
tables. They have been generated with the help of the "eg/bench" program |
458 |
in the JSON::XS distribution, to make it easy to compare on your own |
459 |
system. |
460 |
|
461 |
First comes a comparison between various modules using a very short JSON |
462 |
string: |
463 |
|
464 |
{"method": "handleMessage", "params": ["user1", "we were just talking"], "id": null} |
465 |
|
466 |
It shows the number of encodes/decodes per second (JSON::XS uses the |
467 |
functional interface, while JSON::XS/2 uses the OO interface with |
468 |
pretty-printing and hashkey sorting enabled). Higher is better: |
469 |
|
470 |
module | encode | decode | |
471 |
-----------|------------|------------| |
472 |
JSON | 11488.516 | 7823.035 | |
473 |
JSON::DWIW | 94708.054 | 129094.260 | |
474 |
JSON::PC | 63884.157 | 128528.212 | |
475 |
JSON::Syck | 34898.677 | 42096.911 | |
476 |
JSON::XS | 654027.064 | 396423.669 | |
477 |
JSON::XS/2 | 371564.190 | 371725.613 | |
478 |
-----------+------------+------------+ |
479 |
|
480 |
That is, JSON::XS is more than six times faster than JSON::DWIW on |
481 |
encoding, more than three times faster on decoding, and about thirty |
482 |
times faster than JSON, even with pretty-printing and key sorting. |
483 |
|
484 |
Using a longer test string (roughly 18KB, generated from Yahoo! Locals |
485 |
search API (http://nanoref.com/yahooapis/mgPdGg): |
486 |
|
487 |
module | encode | decode | |
488 |
-----------|------------|------------| |
489 |
JSON | 273.023 | 44.674 | |
490 |
JSON::DWIW | 1089.383 | 1145.704 | |
491 |
JSON::PC | 3097.419 | 2393.921 | |
492 |
JSON::Syck | 514.060 | 843.053 | |
493 |
JSON::XS | 6479.668 | 3636.364 | |
494 |
JSON::XS/2 | 3774.221 | 3599.124 | |
495 |
-----------+------------+------------+ |
496 |
|
497 |
Again, JSON::XS leads by far. |
498 |
|
499 |
On large strings containing lots of high unicode characters, some |
500 |
modules (such as JSON::PC) seem to decode faster than JSON::XS, but the |
501 |
result will be broken due to missing (or wrong) unicode handling. Others |
502 |
refuse to decode or encode properly, so it was impossible to prepare a |
503 |
fair comparison table for that case. |
504 |
|
505 |
RESOURCE LIMITS |
506 |
JSON::XS does not impose any limits on the size of JSON texts or Perl |
507 |
values they represent - if your machine can handle it, JSON::XS will |
508 |
encode or decode it. Future versions might optionally impose structure |
509 |
depth and memory use resource limits. |
510 |
|
511 |
BUGS |
512 |
While the goal of this module is to be correct, that unfortunately does |
513 |
not mean its bug-free, only that I think its design is bug-free. It is |
514 |
still very young and not well-tested. If you keep reporting bugs they |
515 |
will be fixed swiftly, though. |
516 |
|
517 |
AUTHOR |
518 |
Marc Lehmann <schmorp@schmorp.de> |
519 |
http://home.schmorp.de/ |
520 |
|