ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/JSON-XS/README
Revision: 1.6
Committed: Sat Mar 24 19:42:14 2007 UTC (17 years, 1 month ago) by root
Branch: MAIN
CVS Tags: rel-0_5
Changes since 1.5: +53 -38 lines
Log Message:
*** empty log message ***

File Contents

# User Rev Content
1 root 1.1 NAME
2 root 1.2 JSON::XS - JSON serialising/deserialising, done correctly and fast
3 root 1.1
4     SYNOPSIS
5 root 1.2 use JSON::XS;
6 root 1.1
7 root 1.4 # 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 root 1.1 DESCRIPTION
19 root 1.2 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 root 1.4 See MAPPING, below, on how JSON::XS maps perl values to JSON values and
32     vice versa.
33    
34 root 1.2 FEATURES
35     * correct handling of unicode issues
36 root 1.4 This module knows how to handle Unicode, and even documents how and
37     when it does so.
38 root 1.2
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 root 1.6 There is no guessing, no generating of illegal JSON texts by
46 root 1.4 default, and only JSON is accepted as input by default (the latter
47     is a security feature).
48 root 1.2
49     * fast
50 root 1.4 Compared to other JSON modules, this module compares favourably in
51     terms of speed, too.
52 root 1.2
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 root 1.4 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 root 1.2
64     FUNCTIONAL INTERFACE
65     The following convinience methods are provided by this module. They are
66     exported by default:
67    
68 root 1.6 $json_text = to_json $perl_scalar
69 root 1.2 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 root 1.6 This function call is functionally identical to:
74 root 1.2
75 root 1.6 $json_text = JSON::XS->new->utf8->encode ($perl_scalar)
76    
77     except being faster.
78    
79     $perl_scalar = from_json $json_text
80 root 1.2 The opposite of "to_json": expects an UTF-8 (binary) string and
81 root 1.6 tries to parse that as an UTF-8 encoded JSON text, returning the
82 root 1.2 resulting simple scalar or reference. Croaks on error.
83    
84 root 1.6 This function call is functionally identical to:
85    
86     $perl_scalar = JSON::XS->new->utf8->decode ($json_text)
87    
88     except being faster.
89 root 1.2
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 root 1.6 my $json = JSON::XS->new->utf8->space_after->encode ({a => [1,2]})
103 root 1.2 => {"a": [1, 2]}
104    
105 root 1.4 $json = $json->ascii ([$enable])
106     If $enable is true (or missing), then the "encode" method will not
107 root 1.6 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 root 1.2
112     If $enable is false, then the "encode" method will not escape
113 root 1.6 Unicode characters unless required by the JSON syntax. This results
114     in a faster and more compact format.
115 root 1.2
116 root 1.6 JSON::XS->new->ascii (1)->encode ([chr 0x10401])
117     => ["\ud801\udc01"]
118 root 1.2
119 root 1.4 $json = $json->utf8 ([$enable])
120     If $enable is true (or missing), then the "encode" method will
121 root 1.6 encode the JSON result into UTF-8, as required by many protocols,
122 root 1.4 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 root 1.6 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 root 1.2
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 root 1.6 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 root 1.4
144     $json = $json->pretty ([$enable])
145 root 1.2 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 root 1.4 Example, pretty-print some simple structure:
150    
151 root 1.2 my $json = JSON::XS->new->pretty(1)->encode ({a => [1,2]})
152     =>
153     {
154     "a" : [
155     1,
156     2
157     ]
158     }
159    
160 root 1.4 $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 root 1.2
166     If $enable is false, no newlines or indenting will be produced, and
167 root 1.6 the resulting JSON text is guarenteed not to contain any "newlines".
168 root 1.2
169 root 1.6 This setting has no effect when decoding JSON texts.
170 root 1.2
171 root 1.4 $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 root 1.2
176     If $enable is false, then the "encode" method will not add any extra
177     space at those places.
178    
179 root 1.6 This setting has no effect when decoding JSON texts. You will also
180 root 1.2 most likely combine this setting with "space_after".
181    
182 root 1.4 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 root 1.2 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 root 1.6 This setting has no effect when decoding JSON texts.
196 root 1.2
197 root 1.4 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 root 1.2
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 root 1.6 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 root 1.2 contains the same data, as key-value pairs have no inherent ordering
214     in Perl.
215    
216 root 1.6 This setting has no effect when decoding JSON texts.
217 root 1.2
218 root 1.4 $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 root 1.2
224     If $enable is false, then the "encode" method will croak if it isn't
225 root 1.6 passed an arrayref or hashref, as JSON texts must either be an
226 root 1.2 object or array. Likewise, "decode" will croak if given something
227     that is not a JSON object or array.
228    
229 root 1.4 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 root 1.6 memory when your JSON texts are either very very long or you have
240 root 1.4 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 root 1.6 $json_text = $json->encode ($perl_scalar)
258 root 1.2 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 root 1.6 $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 root 1.2
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 root 1.4 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 root 1.5 object keys is preserved (JSON does not preserver object key
288     ordering itself).
289 root 1.4
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 root 1.5 but stays generally the same within a single run of a program.
325 root 1.4 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 root 1.2 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 root 1.3 JSON 1.07
384 root 1.2 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 root 1.3 JSON::PC 0.01
396 root 1.2 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 root 1.6 which is not a valid JSON text.
407 root 1.2
408     Unmaintained (maintainer unresponsive for many months, bugs are not
409     getting fixed).
410    
411 root 1.3 JSON::Syck 0.21
412 root 1.2 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 root 1.6 preferably a way to generate ASCII-only JSON texts).
418 root 1.2
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 root 1.3 JSON::DWIW 0.04
441 root 1.2 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 root 1.6 Does not generate valid JSON texts (key strings are often unquoted,
451     empty keys result in nothing being output)
452 root 1.2
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 root 1.5 First comes a comparison between various modules using a very short JSON
462     string (83 bytes), showing the number of encodes/decodes per second
463     (JSON::XS is the functional interface, while JSON::XS/2 is the OO
464     interface with pretty-printing and hashkey sorting enabled). Higher is
465     better:
466 root 1.2
467     module | encode | decode |
468     -----------|------------|------------|
469     JSON | 14006 | 6820 |
470     JSON::DWIW | 200937 | 120386 |
471     JSON::PC | 85065 | 129366 |
472     JSON::Syck | 59898 | 44232 |
473     JSON::XS | 1171478 | 342435 |
474     JSON::XS/2 | 730760 | 328714 |
475     -----------+------------+------------+
476    
477     That is, JSON::XS is 6 times faster than than JSON::DWIW and about 80
478     times faster than JSON, even with pretty-printing and key sorting.
479    
480 root 1.5 Using a longer test string (roughly 18KB, generated from Yahoo! Locals
481 root 1.2 search API (http://nanoref.com/yahooapis/mgPdGg):
482    
483     module | encode | decode |
484     -----------|------------|------------|
485     JSON | 673 | 38 |
486     JSON::DWIW | 5271 | 770 |
487     JSON::PC | 9901 | 2491 |
488     JSON::Syck | 2360 | 786 |
489     JSON::XS | 37398 | 3202 |
490     JSON::XS/2 | 13765 | 3153 |
491     -----------+------------+------------+
492    
493     Again, JSON::XS leads by far in the encoding case, while still beating
494     every other module in the decoding case.
495    
496 root 1.5 On large strings containing lots of unicode characters, some modules
497     (such as JSON::PC) decode faster than JSON::XS, but the result will be
498     broken due to missing unicode handling. Others refuse to decode or
499     encode properly, so it was impossible to prepare a fair comparison table
500     for that case.
501    
502 root 1.4 RESOURCE LIMITS
503     JSON::XS does not impose any limits on the size of JSON texts or Perl
504     values they represent - if your machine can handle it, JSON::XS will
505     encode or decode it. Future versions might optionally impose structure
506     depth and memory use resource limits.
507 root 1.2
508     BUGS
509     While the goal of this module is to be correct, that unfortunately does
510     not mean its bug-free, only that I think its design is bug-free. It is
511     still very young and not well-tested. If you keep reporting bugs they
512     will be fixed swiftly, though.
513 root 1.1
514     AUTHOR
515     Marc Lehmann <schmorp@schmorp.de>
516     http://home.schmorp.de/
517