… | |
… | |
2 | JSON::XS - JSON serialising/deserialising, done correctly and fast |
2 | JSON::XS - JSON serialising/deserialising, done correctly and fast |
3 | |
3 | |
4 | SYNOPSIS |
4 | SYNOPSIS |
5 | use JSON::XS; |
5 | use JSON::XS; |
6 | |
6 | |
7 | # exported functions, croak on error |
7 | # exported functions, they croak on error |
|
|
8 | # and expect/generate UTF-8 |
8 | |
9 | |
9 | $utf8_encoded_json_text = to_json $perl_hash_or_arrayref; |
10 | $utf8_encoded_json_text = to_json $perl_hash_or_arrayref; |
10 | $perl_hash_or_arrayref = from_json $utf8_encoded_json_text; |
11 | $perl_hash_or_arrayref = from_json $utf8_encoded_json_text; |
11 | |
12 | |
|
|
13 | # objToJson and jsonToObj aliases to to_json and from_json |
|
|
14 | # are exported for compatibility to the JSON module, |
|
|
15 | # but should not be used in new code. |
|
|
16 | |
12 | # oo-interface |
17 | # OO-interface |
13 | |
18 | |
14 | $coder = JSON::XS->new->ascii->pretty->allow_nonref; |
19 | $coder = JSON::XS->new->ascii->pretty->allow_nonref; |
15 | $pretty_printed_unencoded = $coder->encode ($perl_scalar); |
20 | $pretty_printed_unencoded = $coder->encode ($perl_scalar); |
16 | $perl_scalar = $coder->decode ($unicode_json_text); |
21 | $perl_scalar = $coder->decode ($unicode_json_text); |
17 | |
22 | |
… | |
… | |
30 | |
35 | |
31 | See MAPPING, below, on how JSON::XS maps perl values to JSON values and |
36 | See MAPPING, below, on how JSON::XS maps perl values to JSON values and |
32 | vice versa. |
37 | vice versa. |
33 | |
38 | |
34 | FEATURES |
39 | FEATURES |
35 | * correct handling of unicode issues |
40 | * correct unicode handling |
36 | This module knows how to handle Unicode, and even documents how and |
41 | This module knows how to handle Unicode, and even documents how and |
37 | when it does so. |
42 | when it does so. |
38 | |
43 | |
39 | * round-trip integrity |
44 | * round-trip integrity |
40 | When you serialise a perl data structure using only datatypes |
45 | When you serialise a perl data structure using only datatypes |
41 | supported by JSON, the deserialised data structure is identical on |
46 | 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"). |
47 | the Perl level. (e.g. the string "2.0" doesn't suddenly become "2" |
|
|
48 | just because it looks like a number). |
43 | |
49 | |
44 | * strict checking of JSON correctness |
50 | * strict checking of JSON correctness |
45 | There is no guessing, no generating of illegal JSON strings by |
51 | There is no guessing, no generating of illegal JSON texts by |
46 | default, and only JSON is accepted as input by default (the latter |
52 | default, and only JSON is accepted as input by default (the latter |
47 | is a security feature). |
53 | is a security feature). |
48 | |
54 | |
49 | * fast |
55 | * fast |
50 | Compared to other JSON modules, this module compares favourably in |
56 | Compared to other JSON modules, this module compares favourably in |
… | |
… | |
55 | interface. |
61 | interface. |
56 | |
62 | |
57 | * reasonably versatile output formats |
63 | * reasonably versatile output formats |
58 | You can choose between the most compact guarenteed single-line |
64 | You can choose between the most compact guarenteed single-line |
59 | format possible (nice for simple line-based protocols), a pure-ascii |
65 | format possible (nice for simple line-based protocols), a pure-ascii |
60 | format (for when your transport is not 8-bit clean), or a |
66 | format (for when your transport is not 8-bit clean, still supports |
61 | pretty-printed format (for when you want to read that stuff). Or you |
67 | the whole unicode range), or a pretty-printed format (for when you |
62 | can combine those features in whatever way you like. |
68 | want to read that stuff). Or you can combine those features in |
|
|
69 | whatever way you like. |
63 | |
70 | |
64 | FUNCTIONAL INTERFACE |
71 | FUNCTIONAL INTERFACE |
65 | The following convinience methods are provided by this module. They are |
72 | The following convinience methods are provided by this module. They are |
66 | exported by default: |
73 | exported by default: |
67 | |
74 | |
68 | $json_string = to_json $perl_scalar |
75 | $json_text = to_json $perl_scalar |
69 | Converts the given Perl data structure (a simple scalar or a |
76 | 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 |
77 | reference to a hash or array) to a UTF-8 encoded, binary string |
71 | (that is, the string contains octets only). Croaks on error. |
78 | (that is, the string contains octets only). Croaks on error. |
72 | |
79 | |
73 | This function call is functionally identical to |
80 | This function call is functionally identical to: |
|
|
81 | |
74 | "JSON::XS->new->utf8->encode ($perl_scalar)". |
82 | $json_text = JSON::XS->new->utf8->encode ($perl_scalar) |
75 | |
83 | |
|
|
84 | except being faster. |
|
|
85 | |
76 | $perl_scalar = from_json $json_string |
86 | $perl_scalar = from_json $json_text |
77 | The opposite of "to_json": expects an UTF-8 (binary) string and |
87 | The opposite of "to_json": expects an UTF-8 (binary) string and |
78 | tries to parse that as an UTF-8 encoded JSON string, returning the |
88 | tries to parse that as an UTF-8 encoded JSON text, returning the |
79 | resulting simple scalar or reference. Croaks on error. |
89 | resulting simple scalar or reference. Croaks on error. |
80 | |
90 | |
81 | This function call is functionally identical to |
91 | This function call is functionally identical to: |
|
|
92 | |
82 | "JSON::XS->new->utf8->decode ($json_string)". |
93 | $perl_scalar = JSON::XS->new->utf8->decode ($json_text) |
|
|
94 | |
|
|
95 | except being faster. |
83 | |
96 | |
84 | OBJECT-ORIENTED INTERFACE |
97 | OBJECT-ORIENTED INTERFACE |
85 | The object oriented interface lets you configure your own encoding or |
98 | The object oriented interface lets you configure your own encoding or |
86 | decoding style, within the limits of supported formats. |
99 | decoding style, within the limits of supported formats. |
87 | |
100 | |
… | |
… | |
91 | *disabled*. |
104 | *disabled*. |
92 | |
105 | |
93 | The mutators for flags all return the JSON object again and thus |
106 | The mutators for flags all return the JSON object again and thus |
94 | calls can be chained: |
107 | calls can be chained: |
95 | |
108 | |
96 | my $json = JSON::XS->new->utf8(1)->space_after(1)->encode ({a => [1,2]}) |
109 | my $json = JSON::XS->new->utf8->space_after->encode ({a => [1,2]}) |
97 | => {"a": [1, 2]} |
110 | => {"a": [1, 2]} |
98 | |
111 | |
99 | $json = $json->ascii ([$enable]) |
112 | $json = $json->ascii ([$enable]) |
100 | If $enable is true (or missing), then the "encode" method will not |
113 | If $enable is true (or missing), then the "encode" method will not |
101 | generate characters outside the code range 0..127. Any unicode |
114 | generate characters outside the code range 0..127 (which is ASCII). |
102 | characters outside that range will be escaped using either a single |
115 | Any unicode characters outside that range will be escaped using |
103 | \uXXXX (BMP characters) or a double \uHHHH\uLLLLL escape sequence, |
116 | either a single \uXXXX (BMP characters) or a double \uHHHH\uLLLLL |
104 | as per RFC4627. |
117 | escape sequence, as per RFC4627. The resulting encoded JSON text can |
|
|
118 | be treated as a native unicode string, an ascii-encoded, |
|
|
119 | latin1-encoded or UTF-8 encoded string, or any other superset of |
|
|
120 | ASCII. |
105 | |
121 | |
106 | If $enable is false, then the "encode" method will not escape |
122 | If $enable is false, then the "encode" method will not escape |
107 | Unicode characters unless necessary. |
123 | Unicode characters unless required by the JSON syntax or other |
|
|
124 | flags. This results in a faster and more compact format. |
108 | |
125 | |
|
|
126 | The main use for this flag is to produce JSON texts that can be |
|
|
127 | transmitted over a 7-bit channel, as the encoded JSON texts will not |
|
|
128 | contain any 8 bit characters. |
|
|
129 | |
109 | JSON::XS->new->ascii (1)->encode (chr 0x10401) |
130 | JSON::XS->new->ascii (1)->encode ([chr 0x10401]) |
110 | => \ud801\udc01 |
131 | => ["\ud801\udc01"] |
|
|
132 | |
|
|
133 | $json = $json->latin1 ([$enable]) |
|
|
134 | If $enable is true (or missing), then the "encode" method will |
|
|
135 | encode the resulting JSON text as latin1 (or iso-8859-1), escaping |
|
|
136 | any characters outside the code range 0..255. The resulting string |
|
|
137 | can be treated as a latin1-encoded JSON text or a native unicode |
|
|
138 | string. The "decode" method will not be affected in any way by this |
|
|
139 | flag, as "decode" by default expects unicode, which is a strict |
|
|
140 | superset of latin1. |
|
|
141 | |
|
|
142 | If $enable is false, then the "encode" method will not escape |
|
|
143 | Unicode characters unless required by the JSON syntax or other |
|
|
144 | flags. |
|
|
145 | |
|
|
146 | The main use for this flag is efficiently encoding binary data as |
|
|
147 | JSON text, as most octets will not be escaped, resulting in a |
|
|
148 | smaller encoded size. The disadvantage is that the resulting JSON |
|
|
149 | text is encoded in latin1 (and must correctly be treated as such |
|
|
150 | when storing and transfering), a rare encoding for JSON. It is |
|
|
151 | therefore most useful when you want to store data structures known |
|
|
152 | to contain binary data efficiently in files or databases, not when |
|
|
153 | talking to other JSON encoders/decoders. |
|
|
154 | |
|
|
155 | JSON::XS->new->latin1->encode (["\x{89}\x{abc}"] |
|
|
156 | => ["\x{89}\\u0abc"] # (perl syntax, U+abc escaped, U+89 not) |
111 | |
157 | |
112 | $json = $json->utf8 ([$enable]) |
158 | $json = $json->utf8 ([$enable]) |
113 | If $enable is true (or missing), then the "encode" method will |
159 | If $enable is true (or missing), then the "encode" method will |
114 | encode the JSON string into UTF-8, as required by many protocols, |
160 | encode the JSON result into UTF-8, as required by many protocols, |
115 | while the "decode" method expects to be handled an UTF-8-encoded |
161 | while the "decode" method expects to be handled an UTF-8-encoded |
116 | string. Please note that UTF-8-encoded strings do not contain any |
162 | string. Please note that UTF-8-encoded strings do not contain any |
117 | characters outside the range 0..255, they are thus useful for |
163 | characters outside the range 0..255, they are thus useful for |
118 | bytewise/binary I/O. |
164 | bytewise/binary I/O. In future versions, enabling this option might |
|
|
165 | enable autodetection of the UTF-16 and UTF-32 encoding families, as |
|
|
166 | described in RFC4627. |
119 | |
167 | |
120 | If $enable is false, then the "encode" method will return the JSON |
168 | If $enable is false, then the "encode" method will return the JSON |
121 | string as a (non-encoded) unicode string, while "decode" expects |
169 | string as a (non-encoded) unicode string, while "decode" expects |
122 | thus a unicode string. Any decoding or encoding (e.g. to UTF-8 or |
170 | thus a unicode string. Any decoding or encoding (e.g. to UTF-8 or |
123 | UTF-16) needs to be done yourself, e.g. using the Encode module. |
171 | UTF-16) needs to be done yourself, e.g. using the Encode module. |
124 | |
172 | |
125 | Example, output UTF-16-encoded JSON: |
173 | Example, output UTF-16BE-encoded JSON: |
|
|
174 | |
|
|
175 | use Encode; |
|
|
176 | $jsontext = encode "UTF-16BE", JSON::XS->new->encode ($object); |
|
|
177 | |
|
|
178 | Example, decode UTF-32LE-encoded JSON: |
|
|
179 | |
|
|
180 | use Encode; |
|
|
181 | $object = JSON::XS->new->decode (decode "UTF-32LE", $jsontext); |
126 | |
182 | |
127 | $json = $json->pretty ([$enable]) |
183 | $json = $json->pretty ([$enable]) |
128 | This enables (or disables) all of the "indent", "space_before" and |
184 | This enables (or disables) all of the "indent", "space_before" and |
129 | "space_after" (and in the future possibly more) flags in one call to |
185 | "space_after" (and in the future possibly more) flags in one call to |
130 | generate the most readable (or most compact) form possible. |
186 | generate the most readable (or most compact) form possible. |
… | |
… | |
145 | multiline format as output, putting every array member or |
201 | multiline format as output, putting every array member or |
146 | object/hash key-value pair into its own line, identing them |
202 | object/hash key-value pair into its own line, identing them |
147 | properly. |
203 | properly. |
148 | |
204 | |
149 | If $enable is false, no newlines or indenting will be produced, and |
205 | If $enable is false, no newlines or indenting will be produced, and |
150 | the resulting JSON strings is guarenteed not to contain any |
206 | the resulting JSON text is guarenteed not to contain any "newlines". |
151 | "newlines". |
|
|
152 | |
207 | |
153 | This setting has no effect when decoding JSON strings. |
208 | This setting has no effect when decoding JSON texts. |
154 | |
209 | |
155 | $json = $json->space_before ([$enable]) |
210 | $json = $json->space_before ([$enable]) |
156 | If $enable is true (or missing), then the "encode" method will add |
211 | If $enable is true (or missing), then the "encode" method will add |
157 | an extra optional space before the ":" separating keys from values |
212 | an extra optional space before the ":" separating keys from values |
158 | in JSON objects. |
213 | in JSON objects. |
159 | |
214 | |
160 | If $enable is false, then the "encode" method will not add any extra |
215 | If $enable is false, then the "encode" method will not add any extra |
161 | space at those places. |
216 | space at those places. |
162 | |
217 | |
163 | This setting has no effect when decoding JSON strings. You will also |
218 | This setting has no effect when decoding JSON texts. You will also |
164 | most likely combine this setting with "space_after". |
219 | most likely combine this setting with "space_after". |
165 | |
220 | |
166 | Example, space_before enabled, space_after and indent disabled: |
221 | Example, space_before enabled, space_after and indent disabled: |
167 | |
222 | |
168 | {"key" :"value"} |
223 | {"key" :"value"} |
… | |
… | |
174 | pairs and array members. |
229 | pairs and array members. |
175 | |
230 | |
176 | If $enable is false, then the "encode" method will not add any extra |
231 | If $enable is false, then the "encode" method will not add any extra |
177 | space at those places. |
232 | space at those places. |
178 | |
233 | |
179 | This setting has no effect when decoding JSON strings. |
234 | This setting has no effect when decoding JSON texts. |
180 | |
235 | |
181 | Example, space_before and indent disabled, space_after enabled: |
236 | Example, space_before and indent disabled, space_after enabled: |
182 | |
237 | |
183 | {"key": "value"} |
238 | {"key": "value"} |
184 | |
239 | |
… | |
… | |
190 | If $enable is false, then the "encode" method will output key-value |
245 | If $enable is false, then the "encode" method will output key-value |
191 | pairs in the order Perl stores them (which will likely change |
246 | pairs in the order Perl stores them (which will likely change |
192 | between runs of the same script). |
247 | between runs of the same script). |
193 | |
248 | |
194 | This option is useful if you want the same data structure to be |
249 | This option is useful if you want the same data structure to be |
195 | encoded as the same JSON string (given the same overall settings). |
250 | encoded as the same JSON text (given the same overall settings). If |
196 | If it is disabled, the same hash migh be encoded differently even if |
251 | it is disabled, the same hash migh be encoded differently even if |
197 | contains the same data, as key-value pairs have no inherent ordering |
252 | contains the same data, as key-value pairs have no inherent ordering |
198 | in Perl. |
253 | in Perl. |
199 | |
254 | |
200 | This setting has no effect when decoding JSON strings. |
255 | This setting has no effect when decoding JSON texts. |
201 | |
256 | |
202 | $json = $json->allow_nonref ([$enable]) |
257 | $json = $json->allow_nonref ([$enable]) |
203 | If $enable is true (or missing), then the "encode" method can |
258 | If $enable is true (or missing), then the "encode" method can |
204 | convert a non-reference into its corresponding string, number or |
259 | convert a non-reference into its corresponding string, number or |
205 | null JSON value, which is an extension to RFC4627. Likewise, |
260 | null JSON value, which is an extension to RFC4627. Likewise, |
206 | "decode" will accept those JSON values instead of croaking. |
261 | "decode" will accept those JSON values instead of croaking. |
207 | |
262 | |
208 | If $enable is false, then the "encode" method will croak if it isn't |
263 | If $enable is false, then the "encode" method will croak if it isn't |
209 | passed an arrayref or hashref, as JSON strings must either be an |
264 | passed an arrayref or hashref, as JSON texts must either be an |
210 | object or array. Likewise, "decode" will croak if given something |
265 | object or array. Likewise, "decode" will croak if given something |
211 | that is not a JSON object or array. |
266 | that is not a JSON object or array. |
212 | |
267 | |
213 | Example, encode a Perl scalar as JSON value with enabled |
268 | Example, encode a Perl scalar as JSON value with enabled |
214 | "allow_nonref", resulting in an invalid JSON text: |
269 | "allow_nonref", resulting in an invalid JSON text: |
… | |
… | |
218 | |
273 | |
219 | $json = $json->shrink ([$enable]) |
274 | $json = $json->shrink ([$enable]) |
220 | Perl usually over-allocates memory a bit when allocating space for |
275 | Perl usually over-allocates memory a bit when allocating space for |
221 | strings. This flag optionally resizes strings generated by either |
276 | strings. This flag optionally resizes strings generated by either |
222 | "encode" or "decode" to their minimum size possible. This can save |
277 | "encode" or "decode" to their minimum size possible. This can save |
223 | memory when your JSON strings are either very very long or you have |
278 | memory when your JSON texts are either very very long or you have |
224 | many short strings. It will also try to downgrade any strings to |
279 | many short strings. It will also try to downgrade any strings to |
225 | octet-form if possible: perl stores strings internally either in an |
280 | octet-form if possible: perl stores strings internally either in an |
226 | encoding called UTF-X or in octet-form. The latter cannot store |
281 | encoding called UTF-X or in octet-form. The latter cannot store |
227 | everything but uses less space in general. |
282 | everything but uses less space in general (and some buggy Perl or C |
|
|
283 | code might even rely on that internal representation being used). |
|
|
284 | |
|
|
285 | The actual definition of what shrink does might change in future |
|
|
286 | versions, but it will always try to save space at the expense of |
|
|
287 | time. |
228 | |
288 | |
229 | If $enable is true (or missing), the string returned by "encode" |
289 | If $enable is true (or missing), the string returned by "encode" |
230 | will be shrunk-to-fit, while all strings generated by "decode" will |
290 | will be shrunk-to-fit, while all strings generated by "decode" will |
231 | also be shrunk-to-fit. |
291 | also be shrunk-to-fit. |
232 | |
292 | |
… | |
… | |
236 | In the future, this setting might control other things, such as |
296 | In the future, this setting might control other things, such as |
237 | converting strings that look like integers or floats into integers |
297 | converting strings that look like integers or floats into integers |
238 | or floats internally (there is no difference on the Perl level), |
298 | or floats internally (there is no difference on the Perl level), |
239 | saving space. |
299 | saving space. |
240 | |
300 | |
|
|
301 | $json = $json->max_depth ([$maximum_nesting_depth]) |
|
|
302 | Sets the maximum nesting level (default 512) accepted while encoding |
|
|
303 | or decoding. If the JSON text or Perl data structure has an equal or |
|
|
304 | higher nesting level then this limit, then the encoder and decoder |
|
|
305 | will stop and croak at that point. |
|
|
306 | |
|
|
307 | Nesting level is defined by number of hash- or arrayrefs that the |
|
|
308 | encoder needs to traverse to reach a given point or the number of |
|
|
309 | "{" or "[" characters without their matching closing parenthesis |
|
|
310 | crossed to reach a given character in a string. |
|
|
311 | |
|
|
312 | Setting the maximum depth to one disallows any nesting, so that |
|
|
313 | ensures that the object is only a single hash/object or array. |
|
|
314 | |
|
|
315 | The argument to "max_depth" will be rounded up to the next nearest |
|
|
316 | power of two. |
|
|
317 | |
|
|
318 | See SECURITY CONSIDERATIONS, below, for more info on why this is |
|
|
319 | useful. |
|
|
320 | |
241 | $json_string = $json->encode ($perl_scalar) |
321 | $json_text = $json->encode ($perl_scalar) |
242 | Converts the given Perl data structure (a simple scalar or a |
322 | Converts the given Perl data structure (a simple scalar or a |
243 | reference to a hash or array) to its JSON representation. Simple |
323 | reference to a hash or array) to its JSON representation. Simple |
244 | scalars will be converted into JSON string or number sequences, |
324 | scalars will be converted into JSON string or number sequences, |
245 | while references to arrays become JSON arrays and references to |
325 | while references to arrays become JSON arrays and references to |
246 | hashes become JSON objects. Undefined Perl values (e.g. "undef") |
326 | hashes become JSON objects. Undefined Perl values (e.g. "undef") |
247 | become JSON "null" values. Neither "true" nor "false" values will be |
327 | become JSON "null" values. Neither "true" nor "false" values will be |
248 | generated. |
328 | generated. |
249 | |
329 | |
250 | $perl_scalar = $json->decode ($json_string) |
330 | $perl_scalar = $json->decode ($json_text) |
251 | The opposite of "encode": expects a JSON string and tries to parse |
331 | The opposite of "encode": expects a JSON text and tries to parse it, |
252 | it, returning the resulting simple scalar or reference. Croaks on |
332 | returning the resulting simple scalar or reference. Croaks on error. |
253 | error. |
|
|
254 | |
333 | |
255 | JSON numbers and strings become simple Perl scalars. JSON arrays |
334 | JSON numbers and strings become simple Perl scalars. JSON arrays |
256 | become Perl arrayrefs and JSON objects become Perl hashrefs. "true" |
335 | become Perl arrayrefs and JSON objects become Perl hashrefs. "true" |
257 | becomes 1, "false" becomes 0 and "null" becomes "undef". |
336 | becomes 1, "false" becomes 0 and "null" becomes "undef". |
|
|
337 | |
|
|
338 | ($perl_scalar, $characters) = $json->decode_prefix ($json_text) |
|
|
339 | This works like the "decode" method, but instead of raising an |
|
|
340 | exception when there is trailing garbage after the first JSON |
|
|
341 | object, it will silently stop parsing there and return the number of |
|
|
342 | characters consumed so far. |
|
|
343 | |
|
|
344 | This is useful if your JSON texts are not delimited by an outer |
|
|
345 | protocol (which is not the brightest thing to do in the first place) |
|
|
346 | and you need to know where the JSON text ends. |
|
|
347 | |
|
|
348 | JSON::XS->new->decode_prefix ("[1] the tail") |
|
|
349 | => ([], 3) |
258 | |
350 | |
259 | MAPPING |
351 | MAPPING |
260 | This section describes how JSON::XS maps Perl values to JSON values and |
352 | This section describes how JSON::XS maps Perl values to JSON values and |
261 | vice versa. These mappings are designed to "do the right thing" in most |
353 | vice versa. These mappings are designed to "do the right thing" in most |
262 | circumstances automatically, preserving round-tripping characteristics |
354 | circumstances automatically, preserving round-tripping characteristics |
… | |
… | |
267 | refers to the abstract Perl language itself. |
359 | refers to the abstract Perl language itself. |
268 | |
360 | |
269 | JSON -> PERL |
361 | JSON -> PERL |
270 | object |
362 | object |
271 | A JSON object becomes a reference to a hash in Perl. No ordering of |
363 | A JSON object becomes a reference to a hash in Perl. No ordering of |
272 | object keys is preserved. |
364 | object keys is preserved (JSON does not preserver object key |
|
|
365 | ordering itself). |
273 | |
366 | |
274 | array |
367 | array |
275 | A JSON array becomes a reference to an array in Perl. |
368 | A JSON array becomes a reference to an array in Perl. |
276 | |
369 | |
277 | string |
370 | string |
… | |
… | |
301 | truly typeless language, so we can only guess which JSON type is meant |
394 | truly typeless language, so we can only guess which JSON type is meant |
302 | by a Perl value. |
395 | by a Perl value. |
303 | |
396 | |
304 | hash references |
397 | hash references |
305 | Perl hash references become JSON objects. As there is no inherent |
398 | Perl hash references become JSON objects. As there is no inherent |
306 | ordering in hash keys, they will usually be encoded in a |
399 | ordering in hash keys (or JSON objects), they will usually be |
307 | pseudo-random order that can change between runs of the same program |
400 | encoded in a pseudo-random order that can change between runs of the |
308 | but stays generally the same within the single run of a program. |
401 | same program but stays generally the same within a single run of a |
309 | JSON::XS can optionally sort the hash keys (determined by the |
402 | program. JSON::XS can optionally sort the hash keys (determined by |
310 | *canonical* flag), so the same datastructure will serialise to the |
403 | the *canonical* flag), so the same datastructure will serialise to |
311 | same JSON text (given same settings and version of JSON::XS), but |
404 | the same JSON text (given same settings and version of JSON::XS), |
312 | this incurs a runtime overhead. |
405 | but this incurs a runtime overhead and is only rarely useful, e.g. |
|
|
406 | when you want to compare some JSON text against another for |
|
|
407 | equality. |
313 | |
408 | |
314 | array references |
409 | array references |
315 | Perl array references become JSON arrays. |
410 | Perl array references become JSON arrays. |
|
|
411 | |
|
|
412 | other references |
|
|
413 | Other unblessed references are generally not allowed and will cause |
|
|
414 | an exception to be thrown, except for references to the integers 0 |
|
|
415 | and 1, which get turned into "false" and "true" atoms in JSON. You |
|
|
416 | can also use "JSON::XS::false" and "JSON::XS::true" to improve |
|
|
417 | readability. |
|
|
418 | |
|
|
419 | to_json [\0,JSON::XS::true] # yields [false,true] |
316 | |
420 | |
317 | blessed objects |
421 | blessed objects |
318 | Blessed objects are not allowed. JSON::XS currently tries to encode |
422 | Blessed objects are not allowed. JSON::XS currently tries to encode |
319 | their underlying representation (hash- or arrayref), but this |
423 | their underlying representation (hash- or arrayref), but this |
320 | behaviour might change in future versions. |
424 | behaviour might change in future versions. |
… | |
… | |
352 | $x *= 1; # same thing, the choise is yours. |
456 | $x *= 1; # same thing, the choise is yours. |
353 | |
457 | |
354 | You can not currently output JSON booleans or force the type in |
458 | You can not currently output JSON booleans or force the type in |
355 | other, less obscure, ways. Tell me if you need this capability. |
459 | other, less obscure, ways. Tell me if you need this capability. |
356 | |
460 | |
357 | circular data structures |
|
|
358 | Those will be encoded until memory or stackspace runs out. |
|
|
359 | |
|
|
360 | COMPARISON |
461 | COMPARISON |
361 | As already mentioned, this module was created because none of the |
462 | As already mentioned, this module was created because none of the |
362 | existing JSON modules could be made to work correctly. First I will |
463 | existing JSON modules could be made to work correctly. First I will |
363 | describe the problems (or pleasures) I encountered with various existing |
464 | describe the problems (or pleasures) I encountered with various existing |
364 | JSON modules, followed by some benchmark values. JSON::XS was designed |
465 | JSON modules, followed by some benchmark values. JSON::XS was designed |
… | |
… | |
385 | |
486 | |
386 | Has problems handling many Perl values (e.g. regex results and other |
487 | Has problems handling many Perl values (e.g. regex results and other |
387 | magic values will make it croak). |
488 | magic values will make it croak). |
388 | |
489 | |
389 | Does not even generate valid JSON ("{1,2}" gets converted to "{1:2}" |
490 | Does not even generate valid JSON ("{1,2}" gets converted to "{1:2}" |
390 | which is not a valid JSON string. |
491 | which is not a valid JSON text. |
391 | |
492 | |
392 | Unmaintained (maintainer unresponsive for many months, bugs are not |
493 | Unmaintained (maintainer unresponsive for many months, bugs are not |
393 | getting fixed). |
494 | getting fixed). |
394 | |
495 | |
395 | JSON::Syck 0.21 |
496 | JSON::Syck 0.21 |
396 | Very buggy (often crashes). |
497 | Very buggy (often crashes). |
397 | |
498 | |
398 | Very inflexible (no human-readable format supported, format pretty |
499 | Very inflexible (no human-readable format supported, format pretty |
399 | much undocumented. I need at least a format for easy reading by |
500 | much undocumented. I need at least a format for easy reading by |
400 | humans and a single-line compact format for use in a protocol, and |
501 | humans and a single-line compact format for use in a protocol, and |
401 | preferably a way to generate ASCII-only JSON strings). |
502 | preferably a way to generate ASCII-only JSON texts). |
402 | |
503 | |
403 | Completely broken (and confusingly documented) Unicode handling |
504 | Completely broken (and confusingly documented) Unicode handling |
404 | (unicode escapes are not working properly, you need to set |
505 | (unicode escapes are not working properly, you need to set |
405 | ImplicitUnicode to *different* values on en- and decoding to get |
506 | ImplicitUnicode to *different* values on en- and decoding to get |
406 | symmetric behaviour). |
507 | symmetric behaviour). |
… | |
… | |
429 | |
530 | |
430 | Very inflexible. |
531 | Very inflexible. |
431 | |
532 | |
432 | No roundtripping. |
533 | No roundtripping. |
433 | |
534 | |
434 | Does not generate valid JSON (key strings are often unquoted, empty |
535 | Does not generate valid JSON texts (key strings are often unquoted, |
435 | keys result in nothing being output) |
536 | empty keys result in nothing being output) |
436 | |
537 | |
437 | Does not check input for validity. |
538 | Does not check input for validity. |
438 | |
539 | |
439 | SPEED |
540 | SPEED |
440 | It seems that JSON::XS is surprisingly fast, as shown in the following |
541 | It seems that JSON::XS is surprisingly fast, as shown in the following |
441 | tables. They have been generated with the help of the "eg/bench" program |
542 | tables. They have been generated with the help of the "eg/bench" program |
442 | in the JSON::XS distribution, to make it easy to compare on your own |
543 | in the JSON::XS distribution, to make it easy to compare on your own |
443 | system. |
544 | system. |
444 | |
545 | |
445 | First is a comparison between various modules using a very simple JSON |
546 | First comes a comparison between various modules using a very short |
|
|
547 | single-line JSON string: |
|
|
548 | |
|
|
549 | {"method": "handleMessage", "params": ["user1", "we were just talking"], \ |
|
|
550 | "id": null, "array":[1,11,234,-5,1e5,1e7, true, false]} |
|
|
551 | |
446 | string, showing the number of encodes/decodes per second (JSON::XS is |
552 | It shows the number of encodes/decodes per second (JSON::XS uses the |
447 | the functional interface, while JSON::XS/2 is the OO interface with |
553 | functional interface, while JSON::XS/2 uses the OO interface with |
448 | pretty-printing and hashkey sorting enabled). |
554 | pretty-printing and hashkey sorting enabled). Higher is better: |
449 | |
555 | |
450 | module | encode | decode | |
556 | module | encode | decode | |
451 | -----------|------------|------------| |
557 | -----------|------------|------------| |
452 | JSON | 14006 | 6820 | |
558 | JSON | 7645.468 | 4208.613 | |
453 | JSON::DWIW | 200937 | 120386 | |
559 | JSON::DWIW | 68534.379 | 79437.576 | |
454 | JSON::PC | 85065 | 129366 | |
560 | JSON::PC | 65948.176 | 78251.940 | |
455 | JSON::Syck | 59898 | 44232 | |
561 | JSON::Syck | 23379.621 | 28416.694 | |
456 | JSON::XS | 1171478 | 342435 | |
562 | JSON::XS | 388361.481 | 199728.762 | |
457 | JSON::XS/2 | 730760 | 328714 | |
563 | JSON::XS/2 | 218453.333 | 192399.266 | |
|
|
564 | JSON::XS/3 | 338250.323 | 192399.266 | |
|
|
565 | Storable | 15732.573 | 28571.553 | |
458 | -----------+------------+------------+ |
566 | -----------+------------+------------+ |
459 | |
567 | |
460 | That is, JSON::XS is 6 times faster than than JSON::DWIW and about 80 |
568 | That is, JSON::XS is about five times faster than JSON::DWIW on |
|
|
569 | encoding, about three times faster on decoding, and over fourty times |
461 | times faster than JSON, even with pretty-printing and key sorting. |
570 | faster than JSON, even with pretty-printing and key sorting. It also |
|
|
571 | compares favourably to Storable for small amounts of data. |
462 | |
572 | |
463 | Using a longer test string (roughly 8KB, generated from Yahoo! Locals |
573 | Using a longer test string (roughly 18KB, generated from Yahoo! Locals |
464 | search API (http://nanoref.com/yahooapis/mgPdGg): |
574 | search API (http://nanoref.com/yahooapis/mgPdGg): |
465 | |
575 | |
466 | module | encode | decode | |
576 | module | encode | decode | |
467 | -----------|------------|------------| |
577 | -----------|------------|------------| |
468 | JSON | 673 | 38 | |
578 | JSON | 254.685 | 37.665 | |
469 | JSON::DWIW | 5271 | 770 | |
579 | JSON::DWIW | 1014.244 | 1087.678 | |
470 | JSON::PC | 9901 | 2491 | |
580 | JSON::PC | 3602.116 | 2307.352 | |
471 | JSON::Syck | 2360 | 786 | |
581 | JSON::Syck | 558.035 | 776.263 | |
472 | JSON::XS | 37398 | 3202 | |
582 | JSON::XS | 5747.196 | 3543.684 | |
473 | JSON::XS/2 | 13765 | 3153 | |
583 | JSON::XS/2 | 3968.121 | 3589.170 | |
|
|
584 | JSON::XS/3 | 6105.246 | 3561.134 | |
|
|
585 | Storable | 4456.337 | 5320.020 | |
474 | -----------+------------+------------+ |
586 | -----------+------------+------------+ |
475 | |
587 | |
476 | Again, JSON::XS leads by far in the encoding case, while still beating |
588 | Again, JSON::XS leads by far. |
477 | every other module in the decoding case. |
|
|
478 | |
589 | |
479 | RESOURCE LIMITS |
590 | On large strings containing lots of high unicode characters, some |
480 | JSON::XS does not impose any limits on the size of JSON texts or Perl |
591 | modules (such as JSON::PC) seem to decode faster than JSON::XS, but the |
481 | values they represent - if your machine can handle it, JSON::XS will |
592 | result will be broken due to missing (or wrong) unicode handling. Others |
482 | encode or decode it. Future versions might optionally impose structure |
593 | refuse to decode or encode properly, so it was impossible to prepare a |
483 | depth and memory use resource limits. |
594 | fair comparison table for that case. |
|
|
595 | |
|
|
596 | SECURITY CONSIDERATIONS |
|
|
597 | When you are using JSON in a protocol, talking to untrusted potentially |
|
|
598 | hostile creatures requires relatively few measures. |
|
|
599 | |
|
|
600 | First of all, your JSON decoder should be secure, that is, should not |
|
|
601 | have any buffer overflows. Obviously, this module should ensure that and |
|
|
602 | I am trying hard on making that true, but you never know. |
|
|
603 | |
|
|
604 | Second, you need to avoid resource-starving attacks. That means you |
|
|
605 | should limit the size of JSON texts you accept, or make sure then when |
|
|
606 | your resources run out, thats just fine (e.g. by using a separate |
|
|
607 | process that can crash safely). The size of a JSON text in octets or |
|
|
608 | characters is usually a good indication of the size of the resources |
|
|
609 | required to decode it into a Perl structure. |
|
|
610 | |
|
|
611 | Third, JSON::XS recurses using the C stack when decoding objects and |
|
|
612 | arrays. The C stack is a limited resource: for instance, on my amd64 |
|
|
613 | machine with 8MB of stack size I can decode around 180k nested arrays |
|
|
614 | but only 14k nested JSON objects (due to perl itself recursing deeply on |
|
|
615 | croak to free the temporary). If that is exceeded, the program crashes. |
|
|
616 | to be conservative, the default nesting limit is set to 512. If your |
|
|
617 | process has a smaller stack, you should adjust this setting accordingly |
|
|
618 | with the "max_depth" method. |
|
|
619 | |
|
|
620 | And last but least, something else could bomb you that I forgot to think |
|
|
621 | of. In that case, you get to keep the pieces. I am always open for |
|
|
622 | hints, though... |
484 | |
623 | |
485 | BUGS |
624 | BUGS |
486 | While the goal of this module is to be correct, that unfortunately does |
625 | While the goal of this module is to be correct, that unfortunately does |
487 | not mean its bug-free, only that I think its design is bug-free. It is |
626 | not mean its bug-free, only that I think its design is bug-free. It is |
488 | still very young and not well-tested. If you keep reporting bugs they |
627 | still relatively early in its development. If you keep reporting bugs |
489 | will be fixed swiftly, though. |
628 | they will be fixed swiftly, though. |
490 | |
629 | |
491 | AUTHOR |
630 | AUTHOR |
492 | Marc Lehmann <schmorp@schmorp.de> |
631 | Marc Lehmann <schmorp@schmorp.de> |
493 | http://home.schmorp.de/ |
632 | http://home.schmorp.de/ |
494 | |
633 | |