1JSON::PP(3) User Contributed Perl Documentation JSON::PP(3)
2
3
4
6 JSON::PP - JSON::XS compatible pure-Perl module.
7
9 use JSON::PP;
10
11 # exported functions, they croak on error
12 # and expect/generate UTF-8
13
14 $utf8_encoded_json_text = encode_json $perl_hash_or_arrayref;
15 $perl_hash_or_arrayref = decode_json $utf8_encoded_json_text;
16
17 # OO-interface
18
19 $coder = JSON::PP->new->ascii->pretty->allow_nonref;
20 $pretty_printed_unencoded = $coder->encode ($perl_scalar);
21 $perl_scalar = $coder->decode ($unicode_json_text);
22
23 # Note that JSON version 2.0 and above will automatically use
24 # JSON::XS or JSON::PP, so you should be able to just:
25
26 use JSON;
27
29 This module is JSON::XS compatible pure Perl module. (Perl 5.8 or
30 later is recommended)
31
32 JSON::XS is the fastest and most proper JSON module on CPAN. It is
33 written by Marc Lehmann in C, so must be compiled and installed in the
34 used environment.
35
36 JSON::PP is a pure-Perl module and has compatibility to JSON::XS.
37
38 FEATURES
39 · correct unicode handling
40
41 This module knows how to handle Unicode (depending on Perl
42 version).
43
44 See to "A FEW NOTES ON UNICODE AND PERL" in JSON::XS and "UNICODE
45 HANDLING ON PERLS".
46
47 · round-trip integrity
48
49 When you serialise a perl data structure using only datatypes
50 supported by JSON, the deserialised data structure is identical on
51 the Perl level. (e.g. the string "2.0" doesn't suddenly become "2"
52 just because it looks like a number).
53
54 · strict checking of JSON correctness
55
56 There is no guessing, no generating of illegal JSON texts by
57 default, and only JSON is accepted as input by default (the latter
58 is a security feature). But when some options are set, loose
59 chcking features are available.
60
62 Basically, check to JSON or JSON::XS.
63
64 encode_json
65 $json_text = encode_json $perl_scalar
66
67 decode_json
68 $perl_scalar = decode_json $json_text
69
70 JSON::PP::true
71 Returns JSON true value which is blessed object. It "isa"
72 JSON::PP::Boolean object.
73
74 JSON::PP::false
75 Returns JSON false value which is blessed object. It "isa"
76 JSON::PP::Boolean object.
77
78 JSON::PP::null
79 Returns "undef".
80
82 Basically, check to JSON or JSON::XS.
83
84 new
85 $json = new JSON::PP
86
87 Rturns a new JSON::PP object that can be used to de/encode JSON
88 strings.
89
90 ascii
91 $json = $json->ascii([$enable])
92
93 $enabled = $json->get_ascii
94
95 If $enable is true (or missing), then the encode method will not
96 generate characters outside the code range 0..127. Any Unicode
97 characters outside that range will be escaped using either a single
98 \uXXXX or a double \uHHHH\uLLLLL escape sequence, as per RFC4627. (See
99 to "OBJECT-ORIENTED INTERFACE" in JSON::XS).
100
101 In Perl 5.005, there is no character having high value (more than 255).
102 See to "UNICODE HANDLING ON PERLS".
103
104 If $enable is false, then the encode method will not escape Unicode
105 characters unless required by the JSON syntax or other flags. This
106 results in a faster and more compact format.
107
108 JSON::PP->new->ascii(1)->encode([chr 0x10401])
109 => ["\ud801\udc01"]
110
111 latin1
112 $json = $json->latin1([$enable])
113
114 $enabled = $json->get_latin1
115
116 If $enable is true (or missing), then the encode method will encode the
117 resulting JSON text as latin1 (or iso-8859-1), escaping any characters
118 outside the code range 0..255.
119
120 If $enable is false, then the encode method will not escape Unicode
121 characters unless required by the JSON syntax or other flags.
122
123 JSON::XS->new->latin1->encode (["\x{89}\x{abc}"]
124 => ["\x{89}\\u0abc"] # (perl syntax, U+abc escaped, U+89 not)
125
126 See to "UNICODE HANDLING ON PERLS".
127
128 utf8
129 $json = $json->utf8([$enable])
130
131 $enabled = $json->get_utf8
132
133 If $enable is true (or missing), then the encode method will encode the
134 JSON result into UTF-8, as required by many protocols, while the decode
135 method expects to be handled an UTF-8-encoded string. Please note that
136 UTF-8-encoded strings do not contain any characters outside the range
137 0..255, they are thus useful for bytewise/binary I/O.
138
139 (In Perl 5.005, any character outside the range 0..255 does not exist.
140 See to "UNICODE HANDLING ON PERLS".)
141
142 In future versions, enabling this option might enable autodetection of
143 the UTF-16 and UTF-32 encoding families, as described in RFC4627.
144
145 If $enable is false, then the encode method will return the JSON string
146 as a (non-encoded) Unicode string, while decode expects thus a Unicode
147 string. Any decoding or encoding (e.g. to UTF-8 or UTF-16) needs to be
148 done yourself, e.g. using the Encode module.
149
150 Example, output UTF-16BE-encoded JSON:
151
152 use Encode;
153 $jsontext = encode "UTF-16BE", JSON::XS->new->encode ($object);
154
155 Example, decode UTF-32LE-encoded JSON:
156
157 use Encode;
158 $object = JSON::XS->new->decode (decode "UTF-32LE", $jsontext);
159
160 pretty
161 $json = $json->pretty([$enable])
162
163 This enables (or disables) all of the "indent", "space_before" and
164 "space_after" flags in one call to generate the most readable (or most
165 compact) form possible.
166
167 indent
168 $json = $json->indent([$enable])
169
170 $enabled = $json->get_indent
171
172 The default indent space lenght is three. You can use "indent_length"
173 to change the length.
174
175 space_before
176 $json = $json->space_before([$enable])
177
178 $enabled = $json->get_space_before
179
180 space_after
181 $json = $json->space_after([$enable])
182
183 $enabled = $json->get_space_after
184
185 relaxed
186 $json = $json->relaxed([$enable])
187
188 $enabled = $json->get_relaxed
189
190 canonical
191 $json = $json->canonical([$enable])
192
193 $enabled = $json->get_canonical
194
195 If you want your own sorting routine, you can give a code referece or a
196 subroutine name to "sort_by". See to "JSON::PP OWN METHODS".
197
198 allow_nonref
199 $json = $json->allow_nonref([$enable])
200
201 $enabled = $json->get_allow_nonref
202
203 allow_unknown
204 $json = $json->allow_unknown ([$enable])
205
206 $enabled = $json->get_allow_unknown
207
208 allow_blessed
209 $json = $json->allow_blessed([$enable])
210
211 $enabled = $json->get_allow_blessed
212
213 convert_blessed
214 $json = $json->convert_blessed([$enable])
215
216 $enabled = $json->get_convert_blessed
217
218 filter_json_object
219 $json = $json->filter_json_object([$coderef])
220
221 filter_json_single_key_object
222 $json = $json->filter_json_single_key_object($key [=> $coderef])
223
224 shrink
225 $json = $json->shrink([$enable])
226
227 $enabled = $json->get_shrink
228
229 In JSON::XS, this flag resizes strings generated by either "encode" or
230 "decode" to their minimum size possible. It will also try to downgrade
231 any strings to octet-form if possible.
232
233 In JSON::PP, it is noop about resizing strings but tries
234 "utf8::downgrade" to the returned string by "encode". See to utf8.
235
236 See to "OBJECT-ORIENTED INTERFACE" in JSON::XS
237
238 max_depth
239 $json = $json->max_depth([$maximum_nesting_depth])
240
241 $max_depth = $json->get_max_depth
242
243 Sets the maximum nesting level (default 512) accepted while encoding or
244 decoding. If a higher nesting level is detected in JSON text or a Perl
245 data structure, then the encoder and decoder will stop and croak at
246 that point.
247
248 Nesting level is defined by number of hash- or arrayrefs that the
249 encoder needs to traverse to reach a given point or the number of "{"
250 or "[" characters without their matching closing parenthesis crossed to
251 reach a given character in a string.
252
253 If no argument is given, the highest possible setting will be used,
254 which is rarely useful.
255
256 See "SSECURITY CONSIDERATIONS" in JSON::XS for more info on why this is
257 useful.
258
259 When a large value (100 or more) was set and it de/encodes a deep
260 nested object/text, it may raise a warning 'Deep recursion on
261 subroutin' at the perl runtime phase.
262
263 max_size
264 $json = $json->max_size([$maximum_string_size])
265
266 $max_size = $json->get_max_size
267
268 Set the maximum length a JSON text may have (in bytes) where decoding
269 is being attempted. The default is 0, meaning no limit. When "decode"
270 is called on a string that is longer then this many bytes, it will not
271 attempt to decode the string but throw an exception. This setting has
272 no effect on "encode" (yet).
273
274 If no argument is given, the limit check will be deactivated (same as
275 when 0 is specified).
276
277 See "SSECURITY CONSIDERATIONS" in JSON::XS for more info on why this is
278 useful.
279
280 encode
281 $json_text = $json->encode($perl_scalar)
282
283 decode
284 $perl_scalar = $json->decode($json_text)
285
286 decode_prefix
287 ($perl_scalar, $characters) = $json->decode_prefix($json_text)
288
290 In JSON::XS 2.2, incremental parsing feature of JSON texts was
291 experimentally implemented. Please check to "INCREMENTAL PARSING" in
292 JSON::XS.
293
294 [void, scalar or list context] = $json->incr_parse ([$string])
295 This is the central parsing function. It can both append new text
296 and extract objects from the stream accumulated so far (both of
297 these functions are optional).
298
299 If $string is given, then this string is appended to the already
300 existing JSON fragment stored in the $json object.
301
302 After that, if the function is called in void context, it will
303 simply return without doing anything further. This can be used to
304 add more text in as many chunks as you want.
305
306 If the method is called in scalar context, then it will try to
307 extract exactly one JSON object. If that is successful, it will
308 return this object, otherwise it will return "undef". If there is a
309 parse error, this method will croak just as "decode" would do (one
310 can then use "incr_skip" to skip the errornous part). This is the
311 most common way of using the method.
312
313 And finally, in list context, it will try to extract as many
314 objects from the stream as it can find and return them, or the
315 empty list otherwise. For this to work, there must be no separators
316 between the JSON objects or arrays, instead they must be
317 concatenated back-to-back. If an error occurs, an exception will be
318 raised as in the scalar context case. Note that in this case, any
319 previously-parsed JSON texts will be lost.
320
321 $lvalue_string = $json->incr_text
322 This method returns the currently stored JSON fragment as an
323 lvalue, that is, you can manipulate it. This only works when a
324 preceding call to "incr_parse" in scalar context successfully
325 returned an object. Under all other circumstances you must not call
326 this function (I mean it. although in simple tests it might
327 actually work, it will fail under real world conditions). As a
328 special exception, you can also call this method before having
329 parsed anything.
330
331 This function is useful in two cases: a) finding the trailing text
332 after a JSON object or b) parsing multiple JSON objects separated
333 by non-JSON text (such as commas).
334
335 In Perl 5.005, "lvalue" attribute is not available. You must write
336 codes like the below:
337
338 $string = $json->incr_text;
339 $string =~ s/\s*,\s*//;
340 $json->incr_text( $string );
341
342 $json->incr_skip
343 This will reset the state of the incremental parser and will remove
344 the parsed text from the input buffer. This is useful after
345 "incr_parse" died, in which case the input buffer and incremental
346 parser state is left unchanged, to skip the text parsed so far and
347 to reset the parse state.
348
350 allow_singlequote
351 $json = $json->allow_singlequote([$enable])
352
353 If $enable is true (or missing), then "decode" will accept JSON strings
354 quoted by single quotations that are invalid JSON format.
355
356 $json->allow_singlequote->decode({"foo":'bar'});
357 $json->allow_singlequote->decode({'foo':"bar"});
358 $json->allow_singlequote->decode({'foo':'bar'});
359
360 As same as the "relaxed" option, this option may be used to parse
361 application-specific files written by humans.
362
363 allow_barekey
364 $json = $json->allow_barekey([$enable])
365
366 If $enable is true (or missing), then "decode" will accept bare keys of
367 JSON object that are invalid JSON format.
368
369 As same as the "relaxed" option, this option may be used to parse
370 application-specific files written by humans.
371
372 $json->allow_barekey->decode('{foo:"bar"}');
373
374 allow_bignum
375 $json = $json->allow_bignum([$enable])
376
377 If $enable is true (or missing), then "decode" will convert the big
378 integer Perl cannot handle as integer into a Math::BigInt object and
379 convert a floating number (any) into a Math::BigFloat.
380
381 On the contary, "encode" converts "Math::BigInt" objects and
382 "Math::BigFloat" objects into JSON numbers with "allow_blessed" enable.
383
384 $json->allow_nonref->allow_blessed->allow_bignum;
385 $bigfloat = $json->decode('2.000000000000000000000000001');
386 print $json->encode($bigfloat);
387 # => 2.000000000000000000000000001
388
389 See to "MAPPING" in JSON::XS aboout the normal conversion of JSON
390 number.
391
392 loose
393 $json = $json->loose([$enable])
394
395 The unescaped [\x00-\x1f\x22\x2f\x5c] strings are invalid in JSON
396 strings and the module doesn't allow to "decode" to these (except for
397 \x2f). If $enable is true (or missing), then "decode" will accept
398 these unescaped strings.
399
400 $json->loose->decode(qq|["abc
401 def"]|);
402
403 See "SSECURITY CONSIDERATIONS" in JSON::XS.
404
405 escape_slash
406 $json = $json->escape_slash([$enable])
407
408 According to JSON Grammar, slash (U+002F) is escaped. But default
409 JSON::PP (as same as JSON::XS) encodes strings without escaping slash.
410
411 If $enable is true (or missing), then "encode" will escape slashes.
412
413 (OBSOLETED)as_nonblessed
414 $json = $json->as_nonblessed
415
416 (OBSOLETED) If $enable is true (or missing), then "encode" will convert
417 a blessed hash reference or a blessed array reference (contains other
418 blessed references) into JSON members and arrays.
419
420 This feature is effective only when "allow_blessed" is enable.
421
422 indent_length
423 $json = $json->indent_length($length)
424
425 JSON::XS indent space length is 3 and cannot be changed. JSON::PP set
426 the indent space length with the given $length. The default is 3. The
427 acceptable range is 0 to 15.
428
429 sort_by
430 $json = $json->sort_by($function_name)
431 $json = $json->sort_by($subroutine_ref)
432
433 If $function_name or $subroutine_ref are set, its sort routine are used
434 in encoding JSON objects.
435
436 $js = $pc->sort_by(sub { $JSON::PP::a cmp $JSON::PP::b })->encode($obj);
437 # is($js, q|{"a":1,"b":2,"c":3,"d":4,"e":5,"f":6,"g":7,"h":8,"i":9}|);
438
439 $js = $pc->sort_by('own_sort')->encode($obj);
440 # is($js, q|{"a":1,"b":2,"c":3,"d":4,"e":5,"f":6,"g":7,"h":8,"i":9}|);
441
442 sub JSON::PP::own_sort { $JSON::PP::a cmp $JSON::PP::b }
443
444 As the sorting routine runs in the JSON::PP scope, the given subroutine
445 name and the special variables $a, $b will begin 'JSON::PP::'.
446
447 If $integer is set, then the effect is same as "canonical" on.
448
450 For developers.
451
452 PP_encode_box
453 Returns
454
455 {
456 depth => $depth,
457 indent_count => $indent_count,
458 }
459
460 PP_decode_box
461 Returns
462
463 {
464 text => $text,
465 at => $at,
466 ch => $ch,
467 len => $len,
468 depth => $depth,
469 encoding => $encoding,
470 is_valid_utf8 => $is_valid_utf8,
471 };
472
474 See to "MAPPING" in JSON::XS.
475
477 If you do not know about Unicode on Perl well, please check "A FEW
478 NOTES ON UNICODE AND PERL" in JSON::XS.
479
480 Perl 5.8 and later
481 Perl can handle Unicode and the JSON::PP de/encode methods also work
482 properly.
483
484 $json->allow_nonref->encode(chr hex 3042);
485 $json->allow_nonref->encode(chr hex 12345);
486
487 Reuturns "\u3042" and "\ud808\udf45" respectively.
488
489 $json->allow_nonref->decode('"\u3042"');
490 $json->allow_nonref->decode('"\ud808\udf45"');
491
492 Returns UTF-8 encoded strings with UTF8 flag, regarded as "U+3042" and
493 "U+12345".
494
495 Note that the versions from Perl 5.8.0 to 5.8.2, Perl built-in "join"
496 was broken, so JSON::PP wraps the "join" with a subroutine. Thus
497 JSON::PP works slow in the versions.
498
499 Perl 5.6
500 Perl can handle Unicode and the JSON::PP de/encode methods also work.
501
502 Perl 5.005
503 Perl 5.005 is a byte sementics world -- all strings are sequences of
504 bytes. That means the unicode handling is not available.
505
506 In encoding,
507
508 $json->allow_nonref->encode(chr hex 3042); # hex 3042 is 12354.
509 $json->allow_nonref->encode(chr hex 12345); # hex 12345 is 74565.
510
511 Returns "B" and "E", as "chr" takes a value more than 255, it treats as
512 "$value % 256", so the above codes are equivalent to :
513
514 $json->allow_nonref->encode(chr 66);
515 $json->allow_nonref->encode(chr 69);
516
517 In decoding,
518
519 $json->decode('"\u00e3\u0081\u0082"');
520
521 The returned is a byte sequence "0xE3 0x81 0x82" for UTF-8 encoded
522 japanese character ("HIRAGANA LETTER A"). And if it is represented in
523 Unicode code point, "U+3042".
524
525 Next,
526
527 $json->decode('"\u3042"');
528
529 We ordinary expect the returned value is a Unicode character "U+3042".
530 But here is 5.005 world. This is "0xE3 0x81 0x82".
531
532 $json->decode('"\ud808\udf45"');
533
534 This is not a character "U+12345" but bytes - "0xf0 0x92 0x8d 0x85".
535
537 speed
538 memory saving
539
541 Most of the document are copied and modified from JSON::XS doc.
542
543 JSON::XS
544
545 RFC4627 (<http://www.ietf.org/rfc/rfc4627.txt>)
546
548 Makamaka Hannyaharamitu, <makamaka[at]cpan.org>
549
551 Copyright 2007-2010 by Makamaka Hannyaharamitu
552
553 This library is free software; you can redistribute it and/or modify it
554 under the same terms as Perl itself.
555
556
557
558perl v5.12.0 2010-01-07 JSON::PP(3)