1 | =head1 NAME |
1 | =head1 NAME |
2 | |
2 | |
3 | JSON::XS - JSON serialising/deserialising, done correctly and fast |
3 | JSON::XS - JSON serialising/deserialising, done correctly and fast |
|
|
4 | |
|
|
5 | JSON::XS - 正しくて高速な JSON シリアライザ/デシリアライザ |
|
|
6 | (http://fleur.hio.jp/perldoc/mix/lib/JSON/XS.html) |
4 | |
7 | |
5 | =head1 SYNOPSIS |
8 | =head1 SYNOPSIS |
6 | |
9 | |
7 | use JSON::XS; |
10 | use JSON::XS; |
8 | |
11 | |
… | |
… | |
37 | |
40 | |
38 | =head2 FEATURES |
41 | =head2 FEATURES |
39 | |
42 | |
40 | =over 4 |
43 | =over 4 |
41 | |
44 | |
42 | =item * correct unicode handling |
45 | =item * correct Unicode handling |
43 | |
46 | |
44 | This module knows how to handle Unicode, and even documents how and when |
47 | This module knows how to handle Unicode, and even documents how and when |
45 | it does so. |
48 | it does so. |
46 | |
49 | |
47 | =item * round-trip integrity |
50 | =item * round-trip integrity |
… | |
… | |
67 | This module has both a simple functional interface as well as an OO |
70 | This module has both a simple functional interface as well as an OO |
68 | interface. |
71 | interface. |
69 | |
72 | |
70 | =item * reasonably versatile output formats |
73 | =item * reasonably versatile output formats |
71 | |
74 | |
72 | You can choose between the most compact guarenteed single-line format |
75 | You can choose between the most compact guaranteed single-line format |
73 | possible (nice for simple line-based protocols), a pure-ascii format |
76 | possible (nice for simple line-based protocols), a pure-ascii format |
74 | (for when your transport is not 8-bit clean, still supports the whole |
77 | (for when your transport is not 8-bit clean, still supports the whole |
75 | unicode range), or a pretty-printed format (for when you want to read that |
78 | Unicode range), or a pretty-printed format (for when you want to read that |
76 | stuff). Or you can combine those features in whatever way you like. |
79 | stuff). Or you can combine those features in whatever way you like. |
77 | |
80 | |
78 | =back |
81 | =back |
79 | |
82 | |
80 | =cut |
83 | =cut |
81 | |
84 | |
82 | package JSON::XS; |
85 | package JSON::XS; |
83 | |
86 | |
84 | use strict; |
87 | use strict; |
85 | |
88 | |
86 | our $VERSION = '1.4'; |
89 | our $VERSION = '1.53'; |
87 | our @ISA = qw(Exporter); |
90 | our @ISA = qw(Exporter); |
88 | |
91 | |
89 | our @EXPORT = qw(to_json from_json); |
92 | our @EXPORT = qw(to_json from_json); |
90 | |
93 | |
91 | use Exporter; |
94 | use Exporter; |
92 | use XSLoader; |
95 | use XSLoader; |
93 | |
96 | |
94 | =head1 FUNCTIONAL INTERFACE |
97 | =head1 FUNCTIONAL INTERFACE |
95 | |
98 | |
96 | The following convinience methods are provided by this module. They are |
99 | The following convenience methods are provided by this module. They are |
97 | exported by default: |
100 | exported by default: |
98 | |
101 | |
99 | =over 4 |
102 | =over 4 |
100 | |
103 | |
101 | =item $json_text = to_json $perl_scalar |
104 | =item $json_text = to_json $perl_scalar |
102 | |
105 | |
103 | Converts the given Perl data structure (a simple scalar or a reference to |
106 | Converts the given Perl data structure to a UTF-8 encoded, binary string |
104 | a hash or array) to a UTF-8 encoded, binary string (that is, the string contains |
107 | (that is, the string contains octets only). Croaks on error. |
105 | octets only). Croaks on error. |
|
|
106 | |
108 | |
107 | This function call is functionally identical to: |
109 | This function call is functionally identical to: |
108 | |
110 | |
109 | $json_text = JSON::XS->new->utf8->encode ($perl_scalar) |
111 | $json_text = JSON::XS->new->utf8->encode ($perl_scalar) |
110 | |
112 | |
111 | except being faster. |
113 | except being faster. |
112 | |
114 | |
113 | =item $perl_scalar = from_json $json_text |
115 | =item $perl_scalar = from_json $json_text |
114 | |
116 | |
115 | The opposite of C<to_json>: expects an UTF-8 (binary) string and tries to |
117 | The opposite of C<to_json>: expects an UTF-8 (binary) string and tries |
116 | parse that as an UTF-8 encoded JSON text, returning the resulting simple |
118 | to parse that as an UTF-8 encoded JSON text, returning the resulting |
117 | scalar or reference. Croaks on error. |
119 | reference. Croaks on error. |
118 | |
120 | |
119 | This function call is functionally identical to: |
121 | This function call is functionally identical to: |
120 | |
122 | |
121 | $perl_scalar = JSON::XS->new->utf8->decode ($json_text) |
123 | $perl_scalar = JSON::XS->new->utf8->decode ($json_text) |
122 | |
124 | |
… | |
… | |
132 | Perl. |
134 | Perl. |
133 | |
135 | |
134 | =back |
136 | =back |
135 | |
137 | |
136 | |
138 | |
|
|
139 | =head1 A FEW NOTES ON UNICODE AND PERL |
|
|
140 | |
|
|
141 | Since this often leads to confusion, here are a few very clear words on |
|
|
142 | how Unicode works in Perl, modulo bugs. |
|
|
143 | |
|
|
144 | =over 4 |
|
|
145 | |
|
|
146 | =item 1. Perl strings can store characters with ordinal values > 255. |
|
|
147 | |
|
|
148 | This enables you to store Unicode characters as single characters in a |
|
|
149 | Perl string - very natural. |
|
|
150 | |
|
|
151 | =item 2. Perl does I<not> associate an encoding with your strings. |
|
|
152 | |
|
|
153 | Unless you force it to, e.g. when matching it against a regex, or printing |
|
|
154 | the scalar to a file, in which case Perl either interprets your string as |
|
|
155 | locale-encoded text, octets/binary, or as Unicode, depending on various |
|
|
156 | settings. In no case is an encoding stored together with your data, it is |
|
|
157 | I<use> that decides encoding, not any magical metadata. |
|
|
158 | |
|
|
159 | =item 3. The internal utf-8 flag has no meaning with regards to the |
|
|
160 | encoding of your string. |
|
|
161 | |
|
|
162 | Just ignore that flag unless you debug a Perl bug, a module written in |
|
|
163 | XS or want to dive into the internals of perl. Otherwise it will only |
|
|
164 | confuse you, as, despite the name, it says nothing about how your string |
|
|
165 | is encoded. You can have Unicode strings with that flag set, with that |
|
|
166 | flag clear, and you can have binary data with that flag set and that flag |
|
|
167 | clear. Other possibilities exist, too. |
|
|
168 | |
|
|
169 | If you didn't know about that flag, just the better, pretend it doesn't |
|
|
170 | exist. |
|
|
171 | |
|
|
172 | =item 4. A "Unicode String" is simply a string where each character can be |
|
|
173 | validly interpreted as a Unicode codepoint. |
|
|
174 | |
|
|
175 | If you have UTF-8 encoded data, it is no longer a Unicode string, but a |
|
|
176 | Unicode string encoded in UTF-8, giving you a binary string. |
|
|
177 | |
|
|
178 | =item 5. A string containing "high" (> 255) character values is I<not> a UTF-8 string. |
|
|
179 | |
|
|
180 | It's a fact. Learn to live with it. |
|
|
181 | |
|
|
182 | =back |
|
|
183 | |
|
|
184 | I hope this helps :) |
|
|
185 | |
|
|
186 | |
137 | =head1 OBJECT-ORIENTED INTERFACE |
187 | =head1 OBJECT-ORIENTED INTERFACE |
138 | |
188 | |
139 | The object oriented interface lets you configure your own encoding or |
189 | The object oriented interface lets you configure your own encoding or |
140 | decoding style, within the limits of supported formats. |
190 | decoding style, within the limits of supported formats. |
141 | |
191 | |
… | |
… | |
154 | |
204 | |
155 | =item $json = $json->ascii ([$enable]) |
205 | =item $json = $json->ascii ([$enable]) |
156 | |
206 | |
157 | If C<$enable> is true (or missing), then the C<encode> method will not |
207 | If C<$enable> is true (or missing), then the C<encode> method will not |
158 | generate characters outside the code range C<0..127> (which is ASCII). Any |
208 | generate characters outside the code range C<0..127> (which is ASCII). Any |
159 | unicode characters outside that range will be escaped using either a |
209 | Unicode characters outside that range will be escaped using either a |
160 | single \uXXXX (BMP characters) or a double \uHHHH\uLLLLL escape sequence, |
210 | single \uXXXX (BMP characters) or a double \uHHHH\uLLLLL escape sequence, |
161 | as per RFC4627. The resulting encoded JSON text can be treated as a native |
211 | as per RFC4627. The resulting encoded JSON text can be treated as a native |
162 | unicode string, an ascii-encoded, latin1-encoded or UTF-8 encoded string, |
212 | Unicode string, an ascii-encoded, latin1-encoded or UTF-8 encoded string, |
163 | or any other superset of ASCII. |
213 | or any other superset of ASCII. |
164 | |
214 | |
165 | If C<$enable> is false, then the C<encode> method will not escape Unicode |
215 | If C<$enable> is false, then the C<encode> method will not escape Unicode |
166 | characters unless required by the JSON syntax or other flags. This results |
216 | characters unless required by the JSON syntax or other flags. This results |
167 | in a faster and more compact format. |
217 | in a faster and more compact format. |
… | |
… | |
176 | =item $json = $json->latin1 ([$enable]) |
226 | =item $json = $json->latin1 ([$enable]) |
177 | |
227 | |
178 | If C<$enable> is true (or missing), then the C<encode> method will encode |
228 | If C<$enable> is true (or missing), then the C<encode> method will encode |
179 | the resulting JSON text as latin1 (or iso-8859-1), escaping any characters |
229 | the resulting JSON text as latin1 (or iso-8859-1), escaping any characters |
180 | outside the code range C<0..255>. The resulting string can be treated as a |
230 | outside the code range C<0..255>. The resulting string can be treated as a |
181 | latin1-encoded JSON text or a native unicode string. The C<decode> method |
231 | latin1-encoded JSON text or a native Unicode string. The C<decode> method |
182 | will not be affected in any way by this flag, as C<decode> by default |
232 | will not be affected in any way by this flag, as C<decode> by default |
183 | expects unicode, which is a strict superset of latin1. |
233 | expects Unicode, which is a strict superset of latin1. |
184 | |
234 | |
185 | If C<$enable> is false, then the C<encode> method will not escape Unicode |
235 | If C<$enable> is false, then the C<encode> method will not escape Unicode |
186 | characters unless required by the JSON syntax or other flags. |
236 | characters unless required by the JSON syntax or other flags. |
187 | |
237 | |
188 | The main use for this flag is efficiently encoding binary data as JSON |
238 | The main use for this flag is efficiently encoding binary data as JSON |
189 | text, as most octets will not be escaped, resulting in a smaller encoded |
239 | text, as most octets will not be escaped, resulting in a smaller encoded |
190 | size. The disadvantage is that the resulting JSON text is encoded |
240 | size. The disadvantage is that the resulting JSON text is encoded |
191 | in latin1 (and must correctly be treated as such when storing and |
241 | in latin1 (and must correctly be treated as such when storing and |
192 | transfering), a rare encoding for JSON. It is therefore most useful when |
242 | transferring), a rare encoding for JSON. It is therefore most useful when |
193 | you want to store data structures known to contain binary data efficiently |
243 | you want to store data structures known to contain binary data efficiently |
194 | in files or databases, not when talking to other JSON encoders/decoders. |
244 | in files or databases, not when talking to other JSON encoders/decoders. |
195 | |
245 | |
196 | JSON::XS->new->latin1->encode (["\x{89}\x{abc}"] |
246 | JSON::XS->new->latin1->encode (["\x{89}\x{abc}"] |
197 | => ["\x{89}\\u0abc"] # (perl syntax, U+abc escaped, U+89 not) |
247 | => ["\x{89}\\u0abc"] # (perl syntax, U+abc escaped, U+89 not) |
… | |
… | |
205 | range C<0..255>, they are thus useful for bytewise/binary I/O. In future |
255 | range C<0..255>, they are thus useful for bytewise/binary I/O. In future |
206 | versions, enabling this option might enable autodetection of the UTF-16 |
256 | versions, enabling this option might enable autodetection of the UTF-16 |
207 | and UTF-32 encoding families, as described in RFC4627. |
257 | and UTF-32 encoding families, as described in RFC4627. |
208 | |
258 | |
209 | If C<$enable> is false, then the C<encode> method will return the JSON |
259 | If C<$enable> is false, then the C<encode> method will return the JSON |
210 | string as a (non-encoded) unicode string, while C<decode> expects thus a |
260 | string as a (non-encoded) Unicode string, while C<decode> expects thus a |
211 | unicode string. Any decoding or encoding (e.g. to UTF-8 or UTF-16) needs |
261 | Unicode string. Any decoding or encoding (e.g. to UTF-8 or UTF-16) needs |
212 | to be done yourself, e.g. using the Encode module. |
262 | to be done yourself, e.g. using the Encode module. |
213 | |
263 | |
214 | Example, output UTF-16BE-encoded JSON: |
264 | Example, output UTF-16BE-encoded JSON: |
215 | |
265 | |
216 | use Encode; |
266 | use Encode; |
… | |
… | |
240 | |
290 | |
241 | =item $json = $json->indent ([$enable]) |
291 | =item $json = $json->indent ([$enable]) |
242 | |
292 | |
243 | If C<$enable> is true (or missing), then the C<encode> method will use a multiline |
293 | If C<$enable> is true (or missing), then the C<encode> method will use a multiline |
244 | format as output, putting every array member or object/hash key-value pair |
294 | format as output, putting every array member or object/hash key-value pair |
245 | into its own line, identing them properly. |
295 | into its own line, indenting them properly. |
246 | |
296 | |
247 | If C<$enable> is false, no newlines or indenting will be produced, and the |
297 | If C<$enable> is false, no newlines or indenting will be produced, and the |
248 | resulting JSON text is guarenteed not to contain any C<newlines>. |
298 | resulting JSON text is guaranteed not to contain any C<newlines>. |
249 | |
299 | |
250 | This setting has no effect when decoding JSON texts. |
300 | This setting has no effect when decoding JSON texts. |
251 | |
301 | |
252 | =item $json = $json->space_before ([$enable]) |
302 | =item $json = $json->space_before ([$enable]) |
253 | |
303 | |
… | |
… | |
278 | |
328 | |
279 | Example, space_before and indent disabled, space_after enabled: |
329 | Example, space_before and indent disabled, space_after enabled: |
280 | |
330 | |
281 | {"key": "value"} |
331 | {"key": "value"} |
282 | |
332 | |
|
|
333 | =item $json = $json->relaxed ([$enable]) |
|
|
334 | |
|
|
335 | If C<$enable> is true (or missing), then C<decode> will accept some |
|
|
336 | extensions to normal JSON syntax (see below). C<encode> will not be |
|
|
337 | affected in anyway. I<Be aware that this option makes you accept invalid |
|
|
338 | JSON texts as if they were valid!>. I suggest only to use this option to |
|
|
339 | parse application-specific files written by humans (configuration files, |
|
|
340 | resource files etc.) |
|
|
341 | |
|
|
342 | If C<$enable> is false (the default), then C<decode> will only accept |
|
|
343 | valid JSON texts. |
|
|
344 | |
|
|
345 | Currently accepted extensions are: |
|
|
346 | |
|
|
347 | =over 4 |
|
|
348 | |
|
|
349 | =item * list items can have an end-comma |
|
|
350 | |
|
|
351 | JSON I<separates> array elements and key-value pairs with commas. This |
|
|
352 | can be annoying if you write JSON texts manually and want to be able to |
|
|
353 | quickly append elements, so this extension accepts comma at the end of |
|
|
354 | such items not just between them: |
|
|
355 | |
|
|
356 | [ |
|
|
357 | 1, |
|
|
358 | 2, <- this comma not normally allowed |
|
|
359 | ] |
|
|
360 | { |
|
|
361 | "k1": "v1", |
|
|
362 | "k2": "v2", <- this comma not normally allowed |
|
|
363 | } |
|
|
364 | |
|
|
365 | =item * shell-style '#'-comments |
|
|
366 | |
|
|
367 | Whenever JSON allows whitespace, shell-style comments are additionally |
|
|
368 | allowed. They are terminated by the first carriage-return or line-feed |
|
|
369 | character, after which more white-space and comments are allowed. |
|
|
370 | |
|
|
371 | [ |
|
|
372 | 1, # this comment not allowed in JSON |
|
|
373 | # neither this one... |
|
|
374 | ] |
|
|
375 | |
|
|
376 | =back |
|
|
377 | |
283 | =item $json = $json->canonical ([$enable]) |
378 | =item $json = $json->canonical ([$enable]) |
284 | |
379 | |
285 | If C<$enable> is true (or missing), then the C<encode> method will output JSON objects |
380 | If C<$enable> is true (or missing), then the C<encode> method will output JSON objects |
286 | by sorting their keys. This is adding a comparatively high overhead. |
381 | by sorting their keys. This is adding a comparatively high overhead. |
287 | |
382 | |
… | |
… | |
289 | pairs in the order Perl stores them (which will likely change between runs |
384 | pairs in the order Perl stores them (which will likely change between runs |
290 | of the same script). |
385 | of the same script). |
291 | |
386 | |
292 | This option is useful if you want the same data structure to be encoded as |
387 | This option is useful if you want the same data structure to be encoded as |
293 | the same JSON text (given the same overall settings). If it is disabled, |
388 | the same JSON text (given the same overall settings). If it is disabled, |
294 | the same hash migh be encoded differently even if contains the same data, |
389 | the same hash might be encoded differently even if contains the same data, |
295 | as key-value pairs have no inherent ordering in Perl. |
390 | as key-value pairs have no inherent ordering in Perl. |
296 | |
391 | |
297 | This setting has no effect when decoding JSON texts. |
392 | This setting has no effect when decoding JSON texts. |
298 | |
393 | |
299 | =item $json = $json->allow_nonref ([$enable]) |
394 | =item $json = $json->allow_nonref ([$enable]) |
… | |
… | |
316 | |
411 | |
317 | =item $json = $json->allow_blessed ([$enable]) |
412 | =item $json = $json->allow_blessed ([$enable]) |
318 | |
413 | |
319 | If C<$enable> is true (or missing), then the C<encode> method will not |
414 | If C<$enable> is true (or missing), then the C<encode> method will not |
320 | barf when it encounters a blessed reference. Instead, the value of the |
415 | barf when it encounters a blessed reference. Instead, the value of the |
321 | B<convert_blessed> option will decide wether C<null> (C<convert_blessed> |
416 | B<convert_blessed> option will decide whether C<null> (C<convert_blessed> |
322 | disabled or no C<to_json> method found) or a representation of the |
417 | disabled or no C<to_json> method found) or a representation of the |
323 | object (C<convert_blessed> enabled and C<to_json> method found) is being |
418 | object (C<convert_blessed> enabled and C<to_json> method found) is being |
324 | encoded. Has no effect on C<decode>. |
419 | encoded. Has no effect on C<decode>. |
325 | |
420 | |
326 | If C<$enable> is false (the default), then C<encode> will throw an |
421 | If C<$enable> is false (the default), then C<encode> will throw an |
… | |
… | |
391 | |
486 | |
392 | As this callback gets called less often then the C<filter_json_object> |
487 | As this callback gets called less often then the C<filter_json_object> |
393 | one, decoding speed will not usually suffer as much. Therefore, single-key |
488 | one, decoding speed will not usually suffer as much. Therefore, single-key |
394 | objects make excellent targets to serialise Perl objects into, especially |
489 | objects make excellent targets to serialise Perl objects into, especially |
395 | as single-key JSON objects are as close to the type-tagged value concept |
490 | as single-key JSON objects are as close to the type-tagged value concept |
396 | as JSON gets (its basically an ID/VALUE tuple). Of course, JSON does not |
491 | as JSON gets (it's basically an ID/VALUE tuple). Of course, JSON does not |
397 | support this in any way, so you need to make sure your data never looks |
492 | support this in any way, so you need to make sure your data never looks |
398 | like a serialised Perl hash. |
493 | like a serialised Perl hash. |
399 | |
494 | |
400 | Typical names for the single object key are C<__class_whatever__>, or |
495 | Typical names for the single object key are C<__class_whatever__>, or |
401 | C<$__dollars_are_rarely_used__$> or C<}ugly_brace_placement>, or even |
496 | C<$__dollars_are_rarely_used__$> or C<}ugly_brace_placement>, or even |
… | |
… | |
528 | vice versa. These mappings are designed to "do the right thing" in most |
623 | vice versa. These mappings are designed to "do the right thing" in most |
529 | circumstances automatically, preserving round-tripping characteristics |
624 | circumstances automatically, preserving round-tripping characteristics |
530 | (what you put in comes out as something equivalent). |
625 | (what you put in comes out as something equivalent). |
531 | |
626 | |
532 | For the more enlightened: note that in the following descriptions, |
627 | For the more enlightened: note that in the following descriptions, |
533 | lowercase I<perl> refers to the Perl interpreter, while uppcercase I<Perl> |
628 | lowercase I<perl> refers to the Perl interpreter, while uppercase I<Perl> |
534 | refers to the abstract Perl language itself. |
629 | refers to the abstract Perl language itself. |
535 | |
630 | |
536 | |
631 | |
537 | =head2 JSON -> PERL |
632 | =head2 JSON -> PERL |
538 | |
633 | |
539 | =over 4 |
634 | =over 4 |
540 | |
635 | |
541 | =item object |
636 | =item object |
542 | |
637 | |
543 | A JSON object becomes a reference to a hash in Perl. No ordering of object |
638 | A JSON object becomes a reference to a hash in Perl. No ordering of object |
544 | keys is preserved (JSON does not preserver object key ordering itself). |
639 | keys is preserved (JSON does not preserve object key ordering itself). |
545 | |
640 | |
546 | =item array |
641 | =item array |
547 | |
642 | |
548 | A JSON array becomes a reference to an array in Perl. |
643 | A JSON array becomes a reference to an array in Perl. |
549 | |
644 | |
… | |
… | |
553 | are represented by the same codepoints in the Perl string, so no manual |
648 | are represented by the same codepoints in the Perl string, so no manual |
554 | decoding is necessary. |
649 | decoding is necessary. |
555 | |
650 | |
556 | =item number |
651 | =item number |
557 | |
652 | |
558 | A JSON number becomes either an integer or numeric (floating point) |
653 | A JSON number becomes either an integer, numeric (floating point) or |
559 | scalar in perl, depending on its range and any fractional parts. On the |
654 | string scalar in perl, depending on its range and any fractional parts. On |
560 | Perl level, there is no difference between those as Perl handles all the |
655 | the Perl level, there is no difference between those as Perl handles all |
561 | conversion details, but an integer may take slightly less memory and might |
656 | the conversion details, but an integer may take slightly less memory and |
562 | represent more values exactly than (floating point) numbers. |
657 | might represent more values exactly than (floating point) numbers. |
|
|
658 | |
|
|
659 | If the number consists of digits only, JSON::XS will try to represent |
|
|
660 | it as an integer value. If that fails, it will try to represent it as |
|
|
661 | a numeric (floating point) value if that is possible without loss of |
|
|
662 | precision. Otherwise it will preserve the number as a string value. |
|
|
663 | |
|
|
664 | Numbers containing a fractional or exponential part will always be |
|
|
665 | represented as numeric (floating point) values, possibly at a loss of |
|
|
666 | precision. |
|
|
667 | |
|
|
668 | This might create round-tripping problems as numbers might become strings, |
|
|
669 | but as Perl is typeless there is no other way to do it. |
563 | |
670 | |
564 | =item true, false |
671 | =item true, false |
565 | |
672 | |
566 | These JSON atoms become C<JSON::XS::true> and C<JSON::XS::false>, |
673 | These JSON atoms become C<JSON::XS::true> and C<JSON::XS::false>, |
567 | respectively. They are overloaded to act almost exactly like the numbers |
674 | respectively. They are overloaded to act almost exactly like the numbers |
568 | C<1> and C<0>. You can check wether a scalar is a JSON boolean by using |
675 | C<1> and C<0>. You can check whether a scalar is a JSON boolean by using |
569 | the C<JSON::XS::is_bool> function. |
676 | the C<JSON::XS::is_bool> function. |
570 | |
677 | |
571 | =item null |
678 | =item null |
572 | |
679 | |
573 | A JSON null atom becomes C<undef> in Perl. |
680 | A JSON null atom becomes C<undef> in Perl. |
… | |
… | |
609 | to_json [\0,JSON::XS::true] # yields [false,true] |
716 | to_json [\0,JSON::XS::true] # yields [false,true] |
610 | |
717 | |
611 | =item JSON::XS::true, JSON::XS::false |
718 | =item JSON::XS::true, JSON::XS::false |
612 | |
719 | |
613 | These special values become JSON true and JSON false values, |
720 | These special values become JSON true and JSON false values, |
614 | respectively. You cna alos use C<\1> and C<\0> directly if you want. |
721 | respectively. You can also use C<\1> and C<\0> directly if you want. |
615 | |
722 | |
616 | =item blessed objects |
723 | =item blessed objects |
617 | |
724 | |
618 | Blessed objects are not allowed. JSON::XS currently tries to encode their |
725 | Blessed objects are not allowed. JSON::XS currently tries to encode their |
619 | underlying representation (hash- or arrayref), but this behaviour might |
726 | underlying representation (hash- or arrayref), but this behaviour might |
… | |
… | |
636 | to_json [$value] # yields ["5"] |
743 | to_json [$value] # yields ["5"] |
637 | |
744 | |
638 | # undef becomes null |
745 | # undef becomes null |
639 | to_json [undef] # yields [null] |
746 | to_json [undef] # yields [null] |
640 | |
747 | |
641 | You can force the type to be a string by stringifying it: |
748 | You can force the type to be a JSON string by stringifying it: |
642 | |
749 | |
643 | my $x = 3.1; # some variable containing a number |
750 | my $x = 3.1; # some variable containing a number |
644 | "$x"; # stringified |
751 | "$x"; # stringified |
645 | $x .= ""; # another, more awkward way to stringify |
752 | $x .= ""; # another, more awkward way to stringify |
646 | print $x; # perl does it for you, too, quite often |
753 | print $x; # perl does it for you, too, quite often |
647 | |
754 | |
648 | You can force the type to be a number by numifying it: |
755 | You can force the type to be a JSON number by numifying it: |
649 | |
756 | |
650 | my $x = "3"; # some variable containing a string |
757 | my $x = "3"; # some variable containing a string |
651 | $x += 0; # numify it, ensuring it will be dumped as a number |
758 | $x += 0; # numify it, ensuring it will be dumped as a number |
652 | $x *= 1; # same thing, the choise is yours. |
759 | $x *= 1; # same thing, the choice is yours. |
653 | |
760 | |
654 | You can not currently output JSON booleans or force the type in other, |
761 | You can not currently force the type in other, less obscure, ways. Tell me |
655 | less obscure, ways. Tell me if you need this capability. |
762 | if you need this capability. |
656 | |
763 | |
657 | =back |
764 | =back |
658 | |
765 | |
659 | |
766 | |
660 | =head1 COMPARISON |
767 | =head1 COMPARISON |
… | |
… | |
669 | |
776 | |
670 | =item JSON 1.07 |
777 | =item JSON 1.07 |
671 | |
778 | |
672 | Slow (but very portable, as it is written in pure Perl). |
779 | Slow (but very portable, as it is written in pure Perl). |
673 | |
780 | |
674 | Undocumented/buggy Unicode handling (how JSON handles unicode values is |
781 | Undocumented/buggy Unicode handling (how JSON handles Unicode values is |
675 | undocumented. One can get far by feeding it unicode strings and doing |
782 | undocumented. One can get far by feeding it Unicode strings and doing |
676 | en-/decoding oneself, but unicode escapes are not working properly). |
783 | en-/decoding oneself, but Unicode escapes are not working properly). |
677 | |
784 | |
678 | No roundtripping (strings get clobbered if they look like numbers, e.g. |
785 | No round-tripping (strings get clobbered if they look like numbers, e.g. |
679 | the string C<2.0> will encode to C<2.0> instead of C<"2.0">, and that will |
786 | the string C<2.0> will encode to C<2.0> instead of C<"2.0">, and that will |
680 | decode into the number 2. |
787 | decode into the number 2. |
681 | |
788 | |
682 | =item JSON::PC 0.01 |
789 | =item JSON::PC 0.01 |
683 | |
790 | |
684 | Very fast. |
791 | Very fast. |
685 | |
792 | |
686 | Undocumented/buggy Unicode handling. |
793 | Undocumented/buggy Unicode handling. |
687 | |
794 | |
688 | No roundtripping. |
795 | No round-tripping. |
689 | |
796 | |
690 | Has problems handling many Perl values (e.g. regex results and other magic |
797 | Has problems handling many Perl values (e.g. regex results and other magic |
691 | values will make it croak). |
798 | values will make it croak). |
692 | |
799 | |
693 | Does not even generate valid JSON (C<{1,2}> gets converted to C<{1:2}> |
800 | Does not even generate valid JSON (C<{1,2}> gets converted to C<{1:2}> |
… | |
… | |
703 | Very inflexible (no human-readable format supported, format pretty much |
810 | Very inflexible (no human-readable format supported, format pretty much |
704 | undocumented. I need at least a format for easy reading by humans and a |
811 | undocumented. I need at least a format for easy reading by humans and a |
705 | single-line compact format for use in a protocol, and preferably a way to |
812 | single-line compact format for use in a protocol, and preferably a way to |
706 | generate ASCII-only JSON texts). |
813 | generate ASCII-only JSON texts). |
707 | |
814 | |
708 | Completely broken (and confusingly documented) Unicode handling (unicode |
815 | Completely broken (and confusingly documented) Unicode handling (Unicode |
709 | escapes are not working properly, you need to set ImplicitUnicode to |
816 | escapes are not working properly, you need to set ImplicitUnicode to |
710 | I<different> values on en- and decoding to get symmetric behaviour). |
817 | I<different> values on en- and decoding to get symmetric behaviour). |
711 | |
818 | |
712 | No roundtripping (simple cases work, but this depends on wether the scalar |
819 | No round-tripping (simple cases work, but this depends on whether the scalar |
713 | value was used in a numeric context or not). |
820 | value was used in a numeric context or not). |
714 | |
821 | |
715 | Dumping hashes may skip hash values depending on iterator state. |
822 | Dumping hashes may skip hash values depending on iterator state. |
716 | |
823 | |
717 | Unmaintained (maintainer unresponsive for many months, bugs are not |
824 | Unmaintained (maintainer unresponsive for many months, bugs are not |
718 | getting fixed). |
825 | getting fixed). |
719 | |
826 | |
720 | Does not check input for validity (i.e. will accept non-JSON input and |
827 | Does not check input for validity (i.e. will accept non-JSON input and |
721 | return "something" instead of raising an exception. This is a security |
828 | return "something" instead of raising an exception. This is a security |
722 | issue: imagine two banks transfering money between each other using |
829 | issue: imagine two banks transferring money between each other using |
723 | JSON. One bank might parse a given non-JSON request and deduct money, |
830 | JSON. One bank might parse a given non-JSON request and deduct money, |
724 | while the other might reject the transaction with a syntax error. While a |
831 | while the other might reject the transaction with a syntax error. While a |
725 | good protocol will at least recover, that is extra unnecessary work and |
832 | good protocol will at least recover, that is extra unnecessary work and |
726 | the transaction will still not succeed). |
833 | the transaction will still not succeed). |
727 | |
834 | |
728 | =item JSON::DWIW 0.04 |
835 | =item JSON::DWIW 0.04 |
729 | |
836 | |
730 | Very fast. Very natural. Very nice. |
837 | Very fast. Very natural. Very nice. |
731 | |
838 | |
732 | Undocumented unicode handling (but the best of the pack. Unicode escapes |
839 | Undocumented Unicode handling (but the best of the pack. Unicode escapes |
733 | still don't get parsed properly). |
840 | still don't get parsed properly). |
734 | |
841 | |
735 | Very inflexible. |
842 | Very inflexible. |
736 | |
843 | |
737 | No roundtripping. |
844 | No round-tripping. |
738 | |
845 | |
739 | Does not generate valid JSON texts (key strings are often unquoted, empty keys |
846 | Does not generate valid JSON texts (key strings are often unquoted, empty keys |
740 | result in nothing being output) |
847 | result in nothing being output) |
741 | |
848 | |
742 | Does not check input for validity. |
849 | Does not check input for validity. |
… | |
… | |
757 | my $yaml = $to_yaml->encode ($ref) . "\n"; |
864 | my $yaml = $to_yaml->encode ($ref) . "\n"; |
758 | |
865 | |
759 | This will usually generate JSON texts that also parse as valid |
866 | This will usually generate JSON texts that also parse as valid |
760 | YAML. Please note that YAML has hardcoded limits on (simple) object key |
867 | YAML. Please note that YAML has hardcoded limits on (simple) object key |
761 | lengths that JSON doesn't have, so you should make sure that your hash |
868 | lengths that JSON doesn't have, so you should make sure that your hash |
762 | keys are noticably shorter than the 1024 characters YAML allows. |
869 | keys are noticeably shorter than the 1024 characters YAML allows. |
763 | |
870 | |
764 | There might be other incompatibilities that I am not aware of. In general |
871 | There might be other incompatibilities that I am not aware of. In general |
765 | you should not try to generate YAML with a JSON generator or vice versa, |
872 | you should not try to generate YAML with a JSON generator or vice versa, |
766 | or try to parse JSON with a YAML parser or vice versa: chances are high |
873 | or try to parse JSON with a YAML parser or vice versa: chances are high |
767 | that you will run into severe interoperability problems. |
874 | that you will run into severe interoperability problems. |
… | |
… | |
783 | It shows the number of encodes/decodes per second (JSON::XS uses |
890 | It shows the number of encodes/decodes per second (JSON::XS uses |
784 | the functional interface, while JSON::XS/2 uses the OO interface |
891 | the functional interface, while JSON::XS/2 uses the OO interface |
785 | with pretty-printing and hashkey sorting enabled, JSON::XS/3 enables |
892 | with pretty-printing and hashkey sorting enabled, JSON::XS/3 enables |
786 | shrink). Higher is better: |
893 | shrink). Higher is better: |
787 | |
894 | |
788 | Storable | 15779.925 | 14169.946 | |
|
|
789 | -----------+------------+------------+ |
|
|
790 | module | encode | decode | |
895 | module | encode | decode | |
791 | -----------|------------|------------| |
896 | -----------|------------|------------| |
792 | JSON | 4990.842 | 4088.813 | |
897 | JSON | 4990.842 | 4088.813 | |
793 | JSON::DWIW | 51653.990 | 71575.154 | |
898 | JSON::DWIW | 51653.990 | 71575.154 | |
794 | JSON::PC | 65948.176 | 74631.744 | |
899 | JSON::PC | 65948.176 | 74631.744 | |
… | |
… | |
799 | JSON::XS/3 | 338250.323 | 218453.333 | |
904 | JSON::XS/3 | 338250.323 | 218453.333 | |
800 | Storable | 16500.016 | 135300.129 | |
905 | Storable | 16500.016 | 135300.129 | |
801 | -----------+------------+------------+ |
906 | -----------+------------+------------+ |
802 | |
907 | |
803 | That is, JSON::XS is about five times faster than JSON::DWIW on encoding, |
908 | That is, JSON::XS is about five times faster than JSON::DWIW on encoding, |
804 | about three times faster on decoding, and over fourty times faster |
909 | about three times faster on decoding, and over forty times faster |
805 | than JSON, even with pretty-printing and key sorting. It also compares |
910 | than JSON, even with pretty-printing and key sorting. It also compares |
806 | favourably to Storable for small amounts of data. |
911 | favourably to Storable for small amounts of data. |
807 | |
912 | |
808 | Using a longer test string (roughly 18KB, generated from Yahoo! Locals |
913 | Using a longer test string (roughly 18KB, generated from Yahoo! Locals |
809 | search API (http://nanoref.com/yahooapis/mgPdGg): |
914 | search API (http://nanoref.com/yahooapis/mgPdGg): |
… | |
… | |
822 | -----------+------------+------------+ |
927 | -----------+------------+------------+ |
823 | |
928 | |
824 | Again, JSON::XS leads by far (except for Storable which non-surprisingly |
929 | Again, JSON::XS leads by far (except for Storable which non-surprisingly |
825 | decodes faster). |
930 | decodes faster). |
826 | |
931 | |
827 | On large strings containing lots of high unicode characters, some modules |
932 | On large strings containing lots of high Unicode characters, some modules |
828 | (such as JSON::PC) seem to decode faster than JSON::XS, but the result |
933 | (such as JSON::PC) seem to decode faster than JSON::XS, but the result |
829 | will be broken due to missing (or wrong) unicode handling. Others refuse |
934 | will be broken due to missing (or wrong) Unicode handling. Others refuse |
830 | to decode or encode properly, so it was impossible to prepare a fair |
935 | to decode or encode properly, so it was impossible to prepare a fair |
831 | comparison table for that case. |
936 | comparison table for that case. |
832 | |
937 | |
833 | |
938 | |
834 | =head1 SECURITY CONSIDERATIONS |
939 | =head1 SECURITY CONSIDERATIONS |
… | |
… | |
840 | any buffer overflows. Obviously, this module should ensure that and I am |
945 | any buffer overflows. Obviously, this module should ensure that and I am |
841 | trying hard on making that true, but you never know. |
946 | trying hard on making that true, but you never know. |
842 | |
947 | |
843 | Second, you need to avoid resource-starving attacks. That means you should |
948 | Second, you need to avoid resource-starving attacks. That means you should |
844 | limit the size of JSON texts you accept, or make sure then when your |
949 | limit the size of JSON texts you accept, or make sure then when your |
845 | resources run out, thats just fine (e.g. by using a separate process that |
950 | resources run out, that's just fine (e.g. by using a separate process that |
846 | can crash safely). The size of a JSON text in octets or characters is |
951 | can crash safely). The size of a JSON text in octets or characters is |
847 | usually a good indication of the size of the resources required to decode |
952 | usually a good indication of the size of the resources required to decode |
848 | it into a Perl structure. While JSON::XS can check the size of the JSON |
953 | it into a Perl structure. While JSON::XS can check the size of the JSON |
849 | text, it might be too late when you already have it in memory, so you |
954 | text, it might be too late when you already have it in memory, so you |
850 | might want to check the size before you accept the string. |
955 | might want to check the size before you accept the string. |
… | |
… | |
861 | And last but least, something else could bomb you that I forgot to think |
966 | And last but least, something else could bomb you that I forgot to think |
862 | of. In that case, you get to keep the pieces. I am always open for hints, |
967 | of. In that case, you get to keep the pieces. I am always open for hints, |
863 | though... |
968 | though... |
864 | |
969 | |
865 | If you are using JSON::XS to return packets to consumption |
970 | If you are using JSON::XS to return packets to consumption |
866 | by javascript scripts in a browser you should have a look at |
971 | by JavaScript scripts in a browser you should have a look at |
867 | L<http://jpsykes.com/47/practical-csrf-and-json-security> to see wether |
972 | L<http://jpsykes.com/47/practical-csrf-and-json-security> to see whether |
868 | you are vulnerable to some common attack vectors (which really are browser |
973 | you are vulnerable to some common attack vectors (which really are browser |
869 | design bugs, but it is still you who will have to deal with it, as major |
974 | design bugs, but it is still you who will have to deal with it, as major |
870 | browser developers care only for features, not about doing security |
975 | browser developers care only for features, not about doing security |
871 | right). |
976 | right). |
872 | |
977 | |
873 | |
978 | |
|
|
979 | =head1 THREADS |
|
|
980 | |
|
|
981 | This module is I<not> guaranteed to be thread safe and there are no |
|
|
982 | plans to change this until Perl gets thread support (as opposed to the |
|
|
983 | horribly slow so-called "threads" which are simply slow and bloated |
|
|
984 | process simulations - use fork, its I<much> faster, cheaper, better). |
|
|
985 | |
|
|
986 | (It might actually work, but you have been warned). |
|
|
987 | |
|
|
988 | |
874 | =head1 BUGS |
989 | =head1 BUGS |
875 | |
990 | |
876 | While the goal of this module is to be correct, that unfortunately does |
991 | While the goal of this module is to be correct, that unfortunately does |
877 | not mean its bug-free, only that I think its design is bug-free. It is |
992 | not mean its bug-free, only that I think its design is bug-free. It is |
878 | still relatively early in its development. If you keep reporting bugs they |
993 | still relatively early in its development. If you keep reporting bugs they |
879 | will be fixed swiftly, though. |
994 | will be fixed swiftly, though. |
880 | |
995 | |
|
|
996 | Please refrain from using rt.cpan.org or any other bug reporting |
|
|
997 | service. I put the contact address into my modules for a reason. |
|
|
998 | |
881 | =cut |
999 | =cut |
882 | |
1000 | |
883 | our $true = do { bless \(my $dummy = "1"), "JSON::XS::Boolean" }; |
1001 | our $true = do { bless \(my $dummy = 1), "JSON::XS::Boolean" }; |
884 | our $false = do { bless \(my $dummy = "0"), "JSON::XS::Boolean" }; |
1002 | our $false = do { bless \(my $dummy = 0), "JSON::XS::Boolean" }; |
885 | |
1003 | |
886 | sub true() { $true } |
1004 | sub true() { $true } |
887 | sub false() { $false } |
1005 | sub false() { $false } |
888 | |
1006 | |
889 | sub is_bool($) { |
1007 | sub is_bool($) { |