diff options
79 files changed, 10097 insertions, 0 deletions
diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000..a6870d4 --- /dev/null +++ b/.travis.yml @@ -0,0 +1,31 @@ +language: perl +perl: + - "5.8" + - "5.24" +matrix: + include: + - perl: 5.8 + env: JSON_XS_VERSION=4.00 + - perl: 5.8 + env: JSON_XS_VERSION=3.02 + - perl: 5.8 + env: JSON_XS_VERSION=2.34 + - perl: 5.8 + env: JSON_PP_VERSION=2.97001 + - perl: 5.8 + env: JSON_PP_VERSION=2.27400 + - perl: 5.8 + env: JSON_PP_VERSION=2.27101 + - perl: 5.8 + env: CPANEL_JSON_XS_VERSION=3.0218 + - perl: 5.8 + env: CPANEL_JSON_XS_VERSION=4.08 +before_install: + - test $JSON_PP_VERSION && cpanm -n JSON::XS@$JSON_XS_VERSION || true + - test $JSON_XS_VERSION && cpanm -n JSON::XS@$JSON_XS_VERSION || true + - test $CPANEL_JSON_XS_VERSION && cpanm -n Cpanel::JSON::XS@$CPANEL_JSON_XS_VERSION || true +script: + - if test ! $JSON_PP_VERSION && test ! $JSON_XS_VERSION && test ! $CPANEL_JSON_XS_VERSION; then perl Makefile.PL && PERL_JSON_BACKEND=JSON::backportPP make test; else true; fi + - if test $JSON_PP_VERSION; then perl Makefile.PL && PERL_JSON_BACKEND=JSON::PP make test; else true; fi + - if test $JSON_XS_VERSION; then perl Makefile.PL && PERL_JSON_BACKEND=JSON::XS make test; else true; fi + - if test $CPANEL_JSON_XS_VERSION; then perl Makefile.PL && PERL_JSON_BACKEND=Cpanel::JSON::XS make test; else true; fi @@ -0,0 +1,459 @@ +Revision history for Perl extension JSON. + +4.02 2019-02-23 + - fixed a test that breaks if perl is compiled with -Dquadmath + (RT-128589) + +4.01 2019-01-21 + - added boolean function/method that takes a scalar value and + returns a boolean value (David Cantrell) + +4.00 2018-12-07 + - production release + +3.99_01 2018-12-03 + - BACKWARD INCOMPATIBILITY: + As JSON::XS 4.0 changed its policy and enabled allow_nonref + by default, JSON::PP, and thus JSON, also enabled allow_nonref + by default + + - updated backportPP with JSON::PP 3.99_01 + - allow PERL_JSON_PP_USE_B environmental variable to restore + old number detection behavior for compatibility + +2.97001 2017-12-21 + - updated backportPP with JSON::PP 2.97001 + +2.97000 2017-11-21 + - updated backportPP with JSON::PP 2.97000 + - use 5 digit minor version number for a while to avoid + confusion + - fixed is_bool to use blessed() instead of ref() + +2.96 2017-11-20 + - fixed packaging issue + - updated backportPP with JSON::PP 2.96 + - not to use newer Test::More features (RT-122421; ilmari++) + +2.95 2017-11-20 + - updated backportPP with JSON::PP 2.95 + +2.94 2017-05-29 + - fixed VERSION issue caused by VERSION methods added to abstract + backend packages (RT-121892; ppisar++) + - fixed a test for perl 5.6 + +2.93 2017-05-19 + - add VERSION methods to (abstract) backend packages + - explained backward incompatibility about backend method + - updated VERSIONs of backportPP modules + +2.92 2017-05-15 + - production release + +2.91_04 2017-01-10 + - updated backportPP with JSON::PP 2.91_04 + +2.91_03 2017-01-09 + - reworked documentation, based on the one for JSON::XS + - updated backportPP with JSON::PP 2.91_03 + +2.91_02 2016-12-04 + - fixed not to fail tests under Perl 5.25.* (srezic++) + +2.91_01 2016-12-03 + - PERL_JSON_BACKEND now accepts Cpanel::JSON::XS as well + - tweaked tests to support various backends + - made convert_blessed_universally (for Perl 5.18+) and + support_by_pp less harmful + - fixed N/A exit code in Makefile.PL (bulk88) + - various doc patches from gregoa, topaz, zoffix, singingfish, + yanick, dsteinbrunner, Toby Inkster + - removed duplicated tests + - removed base.pm dependency + - updated backportPP with JSON::PP 2.91_01 + +2.90 Wed Oct 30 19:48:43 2013 + + ** INCOMPATIBLE CHANGE ** + + - workaround for JSON::XS version 3.0 or later installed case. + + * the objects returned by JSON::true/false are JSON::PP::Boolean. + * they do not overload 'eq'. + + - changed test cases for this patch. + + t/e02_bool.t + t/e03_bool2.t + t/x17_strange_overload.t + t/xe02_bool.t + t/xe03_bool2.t + t/xe12_boolean.t + +2.61 Thu Oct 17 19:38:55 2013 + - fixed return/or in _incr_parse + reported and patched by MAUKE, sprout and rjbs + https://rt.cpan.org/Public/Bug/Display.html?id=86948 + +2.60 + - $json->is_xs, $json->is_pp was completely broken. + pointed by rt#75867 and emceelam + +2.59 Wed Jun 5 14:35:54 2013 + - PUREPERL_ONLY support was not supported... + and finally remove all PP options from Makefile.PL. + - recommend JSON::XS instead of conditionally requiring it + patched by miyagaw + ( for example, $ cpanm --with-recommends JSON) + - Hide more packages from PAUSE (and other stuff) + patched by miyagawa + +2.58 Thu May 23 09:04:37 2013 + - support PUREPERL_ONLY install option. (rt#84876) + (PERL_ONLY and NO_XS are not yet removed) + - stop installing JSON::XS automatically on Perl 5.18 + +2.57 + - t/x17_strage_overload.t didn't work correctly. + +2.56 Sat Apr 6 09:58:32 2013 + - fixed t/x17_strage_overload.t (rt#84451 by Ricardo Signes) + +2.55 + - update JSON::BackportPP version + +2.54 Fri Apr 5 16:15:08 2013 + - fixed t/19_incr.t on perl >= 5.17.10 (wyant, rt#84154) + pathced by mbeijen and modified with demerphq's patch + - Fixed some spelling (by briandfoy) + - fixed sppeling (by Perlover) + - enhanced documents (Thanks to Justin Hunter and Olof Johansson) + - changed backend module loading for overloaded object behavior + (reported by tokuhirom) + +2.53 Sun May 22 16:11:05 2011 + - made Makefile.PL skipping a installing XS question + when set $ENV{PERL_ONLY} or $ENV{NO_XS} (rt#66820) + +2.52 Sun May 22 15:05:49 2011 + - fixed to_json (pointed and patched by mmcleric in rt#68359) + - backport JSON::PP 2.27200 + * fixed incr_parse docodeing string more correctly (rt#68032 by LCONS) + +2.51 Tue Mar 8 16:03:34 2011 + - import JSON::PP 2.27105 as BackportPP + - fixed documentations (pointed by Britton Kerin and rt#64738) + +2.50 Mon Dec 20 14:56:42 2010 + [JSON] + - stable release + +2.49_01 Sat Nov 27 22:03:17 2010 + [JSON] + - JSON::PP is split away JSON distributino for perl 5.14 + - JSON::backportPP is included in instead. + +2.27 Sun Oct 31 20:32:46 2010 + [JSON::PP] + - Some optimizations (gfx) + [JSON::PP::5005] + - added missing B module varibales (makamaka) + +2.26 Tue Sep 28 17:41:37 2010 + [JSON::PP] + - cleaned up code and enhanced sort option efficiency in encode. + +2.25 Tue Sep 28 16:47:08 2010 + [JSON] + - JSON::Backend::XS::Supportable always executed a needless process + with JSON::XS backend. This made encode/decode a bit slower. + +2.24 Mon Sep 27 10:56:24 2010 + [JSON::PP] + - tweaked code. + - optimized code in hash object encoding. + +2.23 Sun Sep 26 22:08:12 2010 + [JSON::PP] + - modified tied object handling in encode. it made encoding speed faster. + pointed by https://rt.cpan.org/Ticket/Display.html?id=61604 + - modified t/e10_bignum.t + for avoiding a warning in using Math::BigInt dev version + +2.22 Wed Aug 25 12:46:13 2010 + [JSON] + - added JSON::XS installing feature in Makefile.PL + with cpan or cpanm (some points suggested by gfx) + - check that to_json and from_json are not called as methods (CHORNY) + [JSON::PP] + - modified for -Duse64bitall -Duselongdouble compiled perl. + 11_pc_expo.t too. (these are patched by H.Merijn Brand) + +2.21 Mon Apr 5 14:56:52 2010 + [JSON] + - enhanced 'HOW DO I DECODE A DATA FROM OUTER AND ENCODE TO OUTER' + - renamed eg/bench_pp_xs.pl to eg/bench_decode.pl + - added eg/bench_encode.pl + +2.20 Fri Apr 2 12:50:08 2010 + [JSON] + - added eg/bench_pp_xs.pl for benchmark sample + - updated 'INCREMENTAL PARSING' section + [JSON::PP] + - decode_prefix() didn't count a consumed text length properly. + - enhanced XS compatibilty + in the case of decoding a white space garbaged text. + +2.19 Tue Mar 30 13:40:24 2010 + [JSON] + - fixed typo (rt#53535 by Angel Abad) + - added a recommendation + refering to (en|de)code_json to pod (suggested by tokuhirom) + - added 'HOW DO I DECODE A DATA FROM OUTER AND ENCODE TO OUTER' to pod. + +2.18 Tue Mar 23 15:18:10 2010 + [JSON] + - updated document (compatible with JSON::XS 2.29) + [JSON::PP] + - fixed encode an overloaded 'eq' object bug (reported by Alexey A. Kiritchun) + - enhanced an error message compatible to JSON::XS + +2.17 Thu Jan 7 12:23:13 2010 + [JSON] + - fixed a problem caused by JSON::XS backend and support_by_pp option + (rt#52842, rt#52847 by ikegami) + [JSON::PP] + - made compatible with JSON::XS 2.27 + - patched decode for incr_parse (rt#52820 by ikegami) + - relaxed option caused an infinite loop in some condition. + +2.16 Fri Oct 16 15:07:37 2009 + [JSON][JSON::PP] + - made compatible with JSON::XS 2.26 + *indent adds a final newline + - corrected copyrights in JSON::PP58. + +2.15 Tue Jun 2 16:36:42 2009 + [JSON] + - made compatible with JSON::XS 2.24 + - corrected copyrights in some modules. + [JSON::PP] + - modified incr_parse, pointed by Martin J. Evans (rt#46439) + - deleted a meaningless code + +2.14 Tue Feb 24 11:20:24 2009 + [JSON] + - the compatible XS version was miswritten in document. + +2.13 Sat Feb 21 17:01:05 2009 + [JSON::PP] + - decode() didn't upgrade unicode escaped charcters \u0080-\u00ff. + this problem was pointed by rt#43424 (Mika Raento) + [JSON::PP::56] + - fixed utf8::encode/decode emulators bugs. + - defined a missing B module constant in Perl 5.6.0. + (reported by Clinton Pierce) + [JSON::PP::5005] + - _decode_unicode() returned a 0x80-0xff value as UTF8 encoded byte. + [JSON] + - added a refference to JSON::XS's document "JSON and ECMAscript". + - fixed a typo in the document (pointed by Jim Cromie). + +2.12 Wed Jul 16 11:14:35 2008 + [JSON] + - made compatible with JSON::XS 2.22 + + [JSON::PP] + - fixed the incremental parser in negative nest level + (pointed and patched by Yuval Kogman) + +2.11 Tue Jun 17 14:30:01 2008 + [JSON::PP] + - fixed the decoding process which checks number. + regarded number like chars in Unicode (ex. U+FF11) as [\d]. + - enhanced error messages compatible to JSON::XS. + +2.10 Tue Jun 3 18:42:11 2008 + [JSON] + - made compatible with JSON::XS 2.21 + * updated the document. + - added an item pointed by rt#32361 to the doc. + + [JSON::PP] [JSON::PP58] [JSON::PP56] [JSON::PP5005] + - made compatible with JSON::XS 2.21 + * added incr_reset + - removed useless codes. + +2.09 Sun Apr 20 20:45:33 2008 + [JSON] + - made compatible with JSON::XS 2.2 + - changed pod section totally. + + [JSON::PP] 2.20001 + - made compatible witg JSON::XS 2.2 + * lifted the log2 rounding restriction of max_depth and max_size. + * incremental json parsing (EXPERIMENTAL). + * allow_unknown/get_allow_unknown methods. + - the version format was changed. + X.YYZZZ => X.YY is the same as JSON::XS. ZZZ is the PP own version. + - changed pod section totally. + +2.08 Sat Apr 12 22:49:39 2008 + [JSON] + - fixed JSON::Boolean inheritance mechanism. + If the backend is XS with support_by_pp mode and using PP only + support method, JSON::Boolean did not work correctly. + Thanks to hg[at]apteryx's point. + + [JSON::PP] 2.07 + - Now split into JSON::PP58 for Perl 5.8 and lator. + - enhanced an error message compatible to JSON::XS + did not croak when TO_JSON method returns same object as passed. + + [JSON::PP58] + - modified for Perls post 5.8.0 that don't have utf8::is_utf8. + Thanks to Andreas Koenig. + +2.07 Sat Feb 16 15:52:29 2008 + [JSON] + - experimentally added -convert_blessed_universally to define + UNIVERSAL::TO_JSON subroutine. + + use JSON -convert_blessed_universally; + $json->convert_blessed->encode( $blessed ); + + - and as_nonbleesed is obsoleted (not yet removed). OK? + - fixed t/04_pretty.t. + +2.06 Fri Feb 8 16:21:59 2008 + [JSON::PP] 2.06 + - enhanced the XS compatibility for pretty-printing + and the indent handling was broken! + +2.05 Tue Feb 5 13:57:19 2008 + [JSON::PP] 2.05 + - enhanced some XS compatibilities for de/encode. + - now decode_error can dump high (>127) chars. + - enhanced the XS combatilbity of the decoding error. + - fixed the utf8 checker while decoding (is_valid_utf8). + - implemented utf8::downgrade in JSON::PP56. + - enhanced utf8::encode in JSON::PP56. + - made utf8::downgrade return a true in JSON::PP5005. + +2.04 Sat Jan 5 16:10:01 2008 + [JSON] + - fixed a document typo pointed by kawasaki@annocpan + - make DATA handle closed for error mssages in support_by_pp mode. + - switched JSON::Backend::XS::Supportable wrapper de/encode + to changing symbolic tables for croak messages and speed. + - fixed support_by_pp setting + + [JSON::PP] 2.04 + - enhanced the error message compatiblity to XS. + +2.03 Fri Jan 4 14:10:58 2008 + [JSON] + - fixed the description - Transition ways from 1.xx to 2.xx. + $JSON::ConvBlessed compat => $json->allow_blessed->as_nonbleesed + - support_by_pp supports 'as_nonbleesed' (experimental) + - clean up the code for saving memory + + [JSON::PP] 2.03 + - Now the allo_bignum flag also affects the encoding process. + encode() can convert Math::BigInt/Float objects into JSON numbers + - added as_nonblessed option (experimental) + - cleaned up internal function names (renamed camel case names) + +2.02 Wed Dec 26 11:08:19 2007 + [JSON] + - Now support_by_pp allows to use indent_length() + + [JSON::PP] 2.02 + - added get_indent_length + +2.01 Thu Dec 20 11:30:59 2007 + [JSON] + - made the object methods - jsonToObj and objToJson + available for a while with warnings. + +2.00 Wed Dec 19 11:48:04 2007 + [JSON] + - new version! + - modified Makefile.PL for broken Perls (when PERL_DL_NONLAZY = 1). + + [JSON::PP] 2.0104 + - clean up the document. + - use 'subs' instead of CORE::GLOBAL for fixing join() in 5.8.0 - 5.8.2 + - enhanced decoding error messages for JSON::XS compatibility. + - jsonToObj and objToJson warn. + + +1.99_05 Fri Dec 14 18:30:43 2007 + [JSON] + - added a description about the Unicode handling to document. + + [JSON::PP] (2.0103) + - Now the JSON::PP56 unicode handling does not require Unicode::String. + - Now JSON::PP5005 can de/enocde properly within the Perl 5.005 world. + - decode() always utf8::decode()ed to strings. + - decode() returned a big integer as string though the integer is + smaller than it is so. + - a bad know how - added the join() wrapper for Perl 5.8.0 - 5.8.2 bug. + - JSON::PP56 encode() did not handle Unicode properly. + - added a section about the unicode handling on Perls to JSON::PP doc. + +1.99_04 Mon Dec 10 14:28:15 2007 + [JSON] + - modified the tests and source for Perl 5.005 + + [JSON::PP] (2.0102) + - modified some prototypes in JSON::PP5005. + +1.99_03 Mon Dec 10 11:43:02 2007 + [JSON] + - modified tests and document. + in Perl5.8.2 or earlier, decoding with utf8 is broken because of + a Perl side problem. (join() had a bug.) + - modified Makefile.PL for Perl 5.005. + in the version, 'require JSON' is fail.... + + [JSON::PP] (2.0102) + - modified string decode function. + - enhanced error messages for compatibility to JSON::XS. + - enhanced utf8::decode emulator and unpack emulator in JSON::PP56. + +1.99_02 Sun Dec 9 05:06:19 2007 + [JSON::PP] (2.0101) + - decoding with utf8 was broken in Perl 5.10 + as the behaviour of unpack was changed. + - added a fake in JSON::PP5005 (bytes.pm) + - added the missing file JONS::PP::Boolean.pm + +1.99_01 Sat Dec 8 12:01:43 2007 + [JSON] + - released as version 2.0 + this module is incompatible to 1.xx, so check the document. + + [JSON::PP] (2.01 from 0.97) + - updated JSON::PP for compatible to JSON::XS 2.01 + - renamed from_json and to_json to decode_json and encode_json + - added get_* to JSON::PP + - deleted property() from JSON::PP + - deleted strict() and added loose() + - deleted disable_UTF8() and self_encode() + - renamed singlequote to allow_singlequote + - renamed allow_bigint to allow_bignum + - max_depth and max_size round up their arguments. + - added indent_length and sort_by + + +## JSON version 1.xx + +1.15 Wed Nov 14 14:52:31 2007 + - 1.xx final version. + +0.09 Sat Apr 9 15:27:47 2005 + - original version; created by h2xs 1.22 with options + -XA -b 5.5.3 -n JSON + diff --git a/MANIFEST b/MANIFEST new file mode 100644 index 0000000..00b351c --- /dev/null +++ b/MANIFEST @@ -0,0 +1,79 @@ +.travis.yml +Changes +eg/bench_decode.pl +eg/bench_encode.pl +lib/JSON.pm +lib/JSON/backportPP.pm +lib/JSON/backportPP/Boolean.pm +lib/JSON/backportPP/Compat5005.pm +lib/JSON/backportPP/Compat5006.pm +Makefile.PL +MANIFEST This list of files +README +t/00_backend_version.t +t/00_load.t +t/00_load_backport_pp.t +t/00_pod.t +t/01_utf8.t +t/02_error.t +t/03_types.t +t/04_dwiw_encode.t +t/05_dwiw_decode.t +t/06_pc_pretty.t +t/07_pc_esc.t +t/08_pc_base.t +t/09_pc_extra_number.t +t/104_sortby.t +t/105_esc_slash.t +t/106_allow_barekey.t +t/107_allow_singlequote.t +t/108_decode.t +t/109_encode.t +t/10_pc_keysort.t +t/110_bignum.t +t/112_upgrade.t +t/113_overloaded_eq.t +t/114_decode_prefix.t +t/115_tie_ixhash.t +t/116_incr_parse_fixed.t +t/117_numbers.t +t/118_boolean_values.t +t/11_pc_expo.t +t/12_blessed.t +t/13_limit.t +t/14_latin1.t +t/15_prefix.t +t/16_tied.t +t/17_relaxed.t +t/18_json_checker.t +t/19_incr.t +t/20_faihu.t +t/20_unknown.t +t/21_evans.t +t/22_comment_at_eof.t +t/52_object.t +t/99_binary.t +t/e00_func.t +t/e01_property.t +t/e02_bool.t +t/e03_bool2.t +t/e11_conv_blessed_univ.t +t/e90_misc.t +t/gh_28_json_test_suite.t +t/gh_29_trailing_false_value.t +t/rt_116998_wrong_character_offset.t +t/rt_90071_incr_parse.t +t/x00_load.t +t/x02_error.t +t/x12_blessed.t +t/x16_tied.t +t/x17_strange_overload.t +t/xe04_escape_slash.t +t/xe05_indent_length.t +t/xe12_boolean.t +t/xe19_xs_and_suportbypp.t +t/xe20_croak_message.t +t/xe21_is_pp.t +t/zero-mojibake.t +META.yml Module YAML meta-data (added by MakeMaker) +META.json Module JSON meta-data (added by MakeMaker) diff --git a/META.json b/META.json new file mode 100644 index 0000000..fec57bf --- /dev/null +++ b/META.json @@ -0,0 +1,53 @@ +{ + "abstract" : "JSON (JavaScript Object Notation) encoder/decoder", + "author" : [ + "Makamaka Hannyaharamitu, E<lt>makamaka[at]cpan.orgE<gt>" + ], + "dynamic_config" : 1, + "generated_by" : "ExtUtils::MakeMaker version 7.24, CPAN::Meta::Converter version 2.150010", + "license" : [ + "perl_5" + ], + "meta-spec" : { + "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", + "version" : 2 + }, + "name" : "JSON", + "no_index" : { + "directory" : [ + "t", + "inc" + ] + }, + "prereqs" : { + "build" : { + "requires" : { + "ExtUtils::MakeMaker" : "0" + } + }, + "configure" : { + "requires" : { + "ExtUtils::MakeMaker" : "0" + } + }, + "runtime" : { + "recommends" : { + "JSON::XS" : "2.34" + }, + "requires" : { + "Test::More" : "0" + } + } + }, + "release_status" : "stable", + "resources" : { + "bugtracker" : { + "web" : "https://github.com/makamaka/JSON/issues" + }, + "repository" : { + "url" : "https://github.com/makamaka/JSON" + } + }, + "version" : "4.02", + "x_serialization_backend" : "JSON version 4.02" +} diff --git a/META.yml b/META.yml new file mode 100644 index 0000000..fb7f055 --- /dev/null +++ b/META.yml @@ -0,0 +1,28 @@ +--- +abstract: 'JSON (JavaScript Object Notation) encoder/decoder' +author: + - 'Makamaka Hannyaharamitu, E<lt>makamaka[at]cpan.orgE<gt>' +build_requires: + ExtUtils::MakeMaker: '0' +configure_requires: + ExtUtils::MakeMaker: '0' +dynamic_config: 1 +generated_by: 'ExtUtils::MakeMaker version 7.24, CPAN::Meta::Converter version 2.150010' +license: perl +meta-spec: + url: http://module-build.sourceforge.net/META-spec-v1.4.html + version: '1.4' +name: JSON +no_index: + directory: + - t + - inc +recommends: + JSON::XS: '2.34' +requires: + Test::More: '0' +resources: + bugtracker: https://github.com/makamaka/JSON/issues + repository: https://github.com/makamaka/JSON +version: '4.02' +x_serialization_backend: 'CPAN::Meta::YAML version 0.012' diff --git a/Makefile.PL b/Makefile.PL new file mode 100644 index 0000000..7397db8 --- /dev/null +++ b/Makefile.PL @@ -0,0 +1,81 @@ +require 5.00503; +use strict; +use ExtUtils::MakeMaker; + +use lib qw( ./lib ); + +$| = 1; + +$ENV{PERL_JSON_BACKEND} = 'JSON::backportPP'; +eval q| require JSON |; + +if ($@) { + print "Loading lib/JSON.pm failed. No B module?\n"; + print "perl says : $@"; + print "Setting environmental variable 'PERL_DL_NONLAZY' to 0 may help.\n"; + print "No Makefile created.\n"; + exit 0; +} + + +my $version = JSON->VERSION; + +print <<EOF; +Welcome to JSON (v.$version) +============================= + + ** BACKWARD INCOMPATIBILITY ** + +Since version 2.90, stringification (and string comparison) for +JSON::true and JSON::false has not been overloaded. It shouldn't +matter as long as you treat them as boolean values, but a code that +expects they are stringified as "true" or "false" doesn't work as +you have expected any more. + + if (JSON::true eq 'true') { # now fails + + print "The result is $JSON::true now."; # => The result is 1 now. + +And now these boolean values don't inherit JSON::Boolean, either. +When you need to test a value is a JSON boolean value or not, use +JSON::is_bool function, instead of testing the value inherits +a particular boolean class or not. + +EOF + + +WriteMakefile( + 'NAME' => 'JSON', + 'VERSION_FROM' => 'lib/JSON.pm', # finds $VERSION + 'ABSTRACT_FROM' => 'lib/JSON.pm', # retrieve abstract from module + 'AUTHOR' => 'Makamaka Hannyaharamitu, E<lt>makamaka[at]cpan.orgE<gt>', + 'PREREQ_PM' => { + 'Test::More' => 0, + }, + ( $ExtUtils::MakeMaker::VERSION >= 6.3002 ? ('LICENSE' => 'perl', ) : () ), + + ( $ExtUtils::MakeMaker::VERSION >= 6.46 ? ( + 'META_MERGE' => { + resources => { + repository => 'https://github.com/makamaka/JSON', + bugtracker => 'https://github.com/makamaka/JSON/issues', + }, + recommends => { + 'JSON::XS' => JSON->require_xs_version, + }, + } ) : () + ), +); + + +if ($] < 5.006) { # I saw to http://d.hatena.ne.jp/asakusabashi/20051231/p1 + open(IN, "Makefile"); + open(OUT,">Makefile.tmp") || die; + while(<IN>) { + s/PERL_DL_NONLAZY=1//g; + print OUT; + } + close(OUT); + close(IN); + rename("Makefile.tmp" => "Makefile"); +} @@ -0,0 +1,1176 @@ +NAME + JSON - JSON (JavaScript Object Notation) encoder/decoder + +SYNOPSIS + use JSON; # imports encode_json, decode_json, to_json and from_json. + + # simple and fast interfaces (expect/generate UTF-8) + + $utf8_encoded_json_text = encode_json $perl_hash_or_arrayref; + $perl_hash_or_arrayref = decode_json $utf8_encoded_json_text; + + # OO-interface + + $json = JSON->new->allow_nonref; + + $json_text = $json->encode( $perl_scalar ); + $perl_scalar = $json->decode( $json_text ); + + $pretty_printed = $json->pretty->encode( $perl_scalar ); # pretty-printing + +VERSION + 2.93 + +DESCRIPTION + This module is a thin wrapper for JSON::XS-compatible modules with + a few additional features. All the backend modules convert a Perl + data structure to a JSON text as of RFC4627 (which we know is + obsolete but we still stick to; see below for an option to support + part of RFC7159) and vice versa. This module uses JSON::XS by + default, and when JSON::XS is not available, this module falls + back on JSON::PP, which is in the Perl core since 5.14. If + JSON::PP is not available either, this module then falls back on + JSON::backportPP (which is actually JSON::PP in a different .pm + file) bundled in the same distribution as this module. You can + also explicitly specify to use Cpanel::JSON::XS, a fork of + JSON::XS by Reini Urban. + + All these backend modules have slight incompatibilities between + them, including extra features that other modules don't support, + but as long as you use only common features (most important ones + are described below), migration from backend to backend should be + reasonably easy. For details, see each backend module you use. + +CHOOSING BACKEND + This module respects an environmental variable called + "PERL_JSON_BACKEND" when it decides a backend module to use. If + this environmental variable is not set, it tries to load JSON::XS, + and if JSON::XS is not available, it falls back on JSON::PP, and + then JSON::backportPP if JSON::PP is not available either. + + If you always don't want it to fall back on pure perl modules, set + the variable like this ("export" may be "setenv", "set" and the + likes, depending on your environment): + + > export PERL_JSON_BACKEND=JSON::XS + + If you prefer Cpanel::JSON::XS to JSON::XS, then: + + > export PERL_JSON_BACKEND=Cpanel::JSON::XS,JSON::XS,JSON::PP + + You may also want to set this variable at the top of your test + files, in order not to be bothered with incompatibilities between + backends (you need to wrap this in "BEGIN", and set before + actually "use"-ing JSON module, as it decides its backend as soon + as it's loaded): + + BEGIN { $ENV{PERL_JSON_BACKEND}='JSON::backportPP'; } + use JSON; + +USING OPTIONAL FEATURES + There are a few options you can set when you "use" this module: + + -support_by_pp + BEGIN { $ENV{PERL_JSON_BACKEND} = 'JSON::XS' } + + use JSON -support_by_pp; + + my $json = JSON->new; + # escape_slash is for JSON::PP only. + $json->allow_nonref->escape_slash->encode("/"); + + With this option, this module loads its pure perl backend + along with its XS backend (if available), and lets the XS + backend to watch if you set a flag only JSON::PP supports. + When you do, the internal JSON::XS object is replaced with a + newly created JSON::PP object with the setting copied from the + XS object, so that you can use JSON::PP flags (and its slower + "decode"/"encode" methods) from then on. In other words, this + is not something that allows you to hook JSON::XS to change + its behavior while keeping its speed. JSON::XS and JSON::PP + objects are quite different (JSON::XS object is a blessed + scalar reference, while JSON::PP object is a blessed hash + reference), and can't share their internals. + + To avoid needless overhead (by copying settings), you are + advised not to use this option and just to use JSON::PP + explicitly when you need JSON::PP features. + + -convert_blessed_universally + use JSON -convert_blessed_universally; + + my $json = JSON->new->allow_nonref->convert_blessed; + my $object = bless {foo => 'bar'}, 'Foo'; + $json->encode($object); # => {"foo":"bar"} + + JSON::XS-compatible backend modules don't encode blessed + objects by default (except for their boolean values, which are + typically blessed JSON::PP::Boolean objects). If you need to + encode a data structure that may contain objects, you usually + need to look into the structure and replace objects with + alternative non-blessed values, or enable "convert_blessed" + and provide a "TO_JSON" method for each object's (base) class + that may be found in the structure, in order to let the + methods replace the objects with whatever scalar values the + methods return. + + If you need to serialise data structures that may contain + arbitrary objects, it's probably better to use other + serialisers (such as Sereal or Storable for example), but if + you do want to use this module for that purpose, + "-convert_blessed_universally" option may help, which tweaks + "encode" method of the backend to install "UNIVERSAL::TO_JSON" + method (locally) before encoding, so that all the objects that + don't have their own "TO_JSON" method can fall back on the + method in the "UNIVERSAL" namespace. Note that you still need + to enable "convert_blessed" flag to actually encode objects in + a data structure, and "UNIVERSAL::TO_JSON" method installed by + this option only converts blessed hash/array references into + their unblessed clone (including private keys/values that are + not supposed to be exposed). Other blessed references will be + converted into null. + + This feature is experimental and may be removed in the future. + + -no_export + When you don't want to import functional interfaces from a + module, you usually supply "()" to its "use" statement. + + use JSON (); # no functional interfaces + + If you don't want to import functional interfaces, but you + also want to use any of the above options, add "-no_export" to + the option list. + + # no functional interfaces, while JSON::PP support is enabled. + use JSON -support_by_pp, -no_export; + +FUNCTIONAL INTERFACE + This section is taken from JSON::XS. "encode_json" and + "decode_json" are exported by default. + + This module also exports "to_json" and "from_json" for backward + compatibility. These are slower, and may expect/generate different + stuff from what "encode_json" and "decode_json" do, depending on + their options. It's better just to use Object-Oriented interfaces + than using these two functions. + + encode_json + $json_text = encode_json $perl_scalar + + Converts the given Perl data structure to a UTF-8 encoded, binary + string (that is, the string contains octets only). Croaks on + error. + + This function call is functionally identical to: + + $json_text = JSON->new->utf8->encode($perl_scalar) + + Except being faster. + + decode_json + $perl_scalar = decode_json $json_text + + The opposite of "encode_json": expects an UTF-8 (binary) string + and tries to parse that as an UTF-8 encoded JSON text, returning + the resulting reference. Croaks on error. + + This function call is functionally identical to: + + $perl_scalar = JSON->new->utf8->decode($json_text) + + Except being faster. + + to_json + $json_text = to_json($perl_scalar[, $optional_hashref]) + + Converts the given Perl data structure to a Unicode string by + default. Croaks on error. + + Basically, this function call is functionally identical to: + + $json_text = JSON->new->encode($perl_scalar) + + Except being slower. + + You can pass an optional hash reference to modify its behavior, + but that may change what "to_json" expects/generates (see + "ENCODING/CODESET FLAG NOTES" for details). + + $json_text = to_json($perl_scalar, {utf8 => 1, pretty => 1}) + # => JSON->new->utf8(1)->pretty(1)->encode($perl_scalar) + + from_json + $perl_scalar = from_json($json_text[, $optional_hashref]) + + The opposite of "to_json": expects a Unicode string and tries to + parse it, returning the resulting reference. Croaks on error. + + Basically, this function call is functionally identical to: + + $perl_scalar = JSON->new->decode($json_text) + + You can pass an optional hash reference to modify its behavior, + but that may change what "from_json" expects/generates (see + "ENCODING/CODESET FLAG NOTES" for details). + + $perl_scalar = from_json($json_text, {utf8 => 1}) + # => JSON->new->utf8(1)->decode($json_text) + + JSON::is_bool + $is_boolean = JSON::is_bool($scalar) + + Returns true if the passed scalar represents either JSON::true or + JSON::false, two constants that act like 1 and 0 respectively and + are also used to represent JSON "true" and "false" in Perl + strings. + + See MAPPING, below, for more information on how JSON values are + mapped to Perl. + +COMMON OBJECT-ORIENTED INTERFACE + This section is also taken from JSON::XS. + + The object oriented interface lets you configure your own encoding + or decoding style, within the limits of supported formats. + + new + $json = JSON->new + + Creates a new JSON::XS-compatible backend object that can be used + to de/encode JSON strings. All boolean flags described below are + by default *disabled*. + + The mutators for flags all return the backend object again and + thus calls can be chained: + + my $json = JSON->new->utf8->space_after->encode({a => [1,2]}) + => {"a": [1, 2]} + + ascii + $json = $json->ascii([$enable]) + + $enabled = $json->get_ascii + + If $enable is true (or missing), then the "encode" method will not + generate characters outside the code range 0..127 (which is + ASCII). Any Unicode characters outside that range will be escaped + using either a single \uXXXX (BMP characters) or a double + \uHHHH\uLLLLL escape sequence, as per RFC4627. The resulting + encoded JSON text can be treated as a native Unicode string, an + ascii-encoded, latin1-encoded or UTF-8 encoded string, or any + other superset of ASCII. + + If $enable is false, then the "encode" method will not escape + Unicode characters unless required by the JSON syntax or other + flags. This results in a faster and more compact format. + + See also the section *ENCODING/CODESET FLAG NOTES* later in this + document. + + The main use for this flag is to produce JSON texts that can be + transmitted over a 7-bit channel, as the encoded JSON texts will + not contain any 8 bit characters. + + JSON->new->ascii(1)->encode([chr 0x10401]) + => ["\ud801\udc01"] + + latin1 + $json = $json->latin1([$enable]) + + $enabled = $json->get_latin1 + + If $enable is true (or missing), then the "encode" method will + encode the resulting JSON text as latin1 (or iso-8859-1), escaping + any characters outside the code range 0..255. The resulting string + can be treated as a latin1-encoded JSON text or a native Unicode + string. The "decode" method will not be affected in any way by + this flag, as "decode" by default expects Unicode, which is a + strict superset of latin1. + + If $enable is false, then the "encode" method will not escape + Unicode characters unless required by the JSON syntax or other + flags. + + See also the section *ENCODING/CODESET FLAG NOTES* later in this + document. + + The main use for this flag is efficiently encoding binary data as + JSON text, as most octets will not be escaped, resulting in a + smaller encoded size. The disadvantage is that the resulting JSON + text is encoded in latin1 (and must correctly be treated as such + when storing and transferring), a rare encoding for JSON. It is + therefore most useful when you want to store data structures known + to contain binary data efficiently in files or databases, not when + talking to other JSON encoders/decoders. + + JSON->new->latin1->encode (["\x{89}\x{abc}"] + => ["\x{89}\\u0abc"] # (perl syntax, U+abc escaped, U+89 not) + + utf8 + $json = $json->utf8([$enable]) + + $enabled = $json->get_utf8 + + If $enable is true (or missing), then the "encode" method will + encode the JSON result into UTF-8, as required by many protocols, + while the "decode" method expects to be handled an UTF-8-encoded + string. Please note that UTF-8-encoded strings do not contain any + characters outside the range 0..255, they are thus useful for + bytewise/binary I/O. In future versions, enabling this option + might enable autodetection of the UTF-16 and UTF-32 encoding + families, as described in RFC4627. + + If $enable is false, then the "encode" method will return the JSON + string as a (non-encoded) Unicode string, while "decode" expects + thus a Unicode string. Any decoding or encoding (e.g. to UTF-8 or + UTF-16) needs to be done yourself, e.g. using the Encode module. + + See also the section *ENCODING/CODESET FLAG NOTES* later in this + document. + + Example, output UTF-16BE-encoded JSON: + + use Encode; + $jsontext = encode "UTF-16BE", JSON->new->encode ($object); + + Example, decode UTF-32LE-encoded JSON: + + use Encode; + $object = JSON->new->decode (decode "UTF-32LE", $jsontext); + + pretty + $json = $json->pretty([$enable]) + + This enables (or disables) all of the "indent", "space_before" and + "space_after" (and in the future possibly more) flags in one call + to generate the most readable (or most compact) form possible. + + indent + $json = $json->indent([$enable]) + + $enabled = $json->get_indent + + If $enable is true (or missing), then the "encode" method will use + a multiline format as output, putting every array member or + object/hash key-value pair into its own line, indenting them + properly. + + If $enable is false, no newlines or indenting will be produced, + and the resulting JSON text is guaranteed not to contain any + "newlines". + + This setting has no effect when decoding JSON texts. + + space_before + $json = $json->space_before([$enable]) + + $enabled = $json->get_space_before + + If $enable is true (or missing), then the "encode" method will add + an extra optional space before the ":" separating keys from values + in JSON objects. + + If $enable is false, then the "encode" method will not add any + extra space at those places. + + This setting has no effect when decoding JSON texts. You will also + most likely combine this setting with "space_after". + + Example, space_before enabled, space_after and indent disabled: + + {"key" :"value"} + + space_after + $json = $json->space_after([$enable]) + + $enabled = $json->get_space_after + + If $enable is true (or missing), then the "encode" method will add + an extra optional space after the ":" separating keys from values + in JSON objects and extra whitespace after the "," separating + key-value pairs and array members. + + If $enable is false, then the "encode" method will not add any + extra space at those places. + + This setting has no effect when decoding JSON texts. + + Example, space_before and indent disabled, space_after enabled: + + {"key": "value"} + + relaxed + $json = $json->relaxed([$enable]) + + $enabled = $json->get_relaxed + + If $enable is true (or missing), then "decode" will accept some + extensions to normal JSON syntax (see below). "encode" will not be + affected in anyway. *Be aware that this option makes you accept + invalid JSON texts as if they were valid!*. I suggest only to use + this option to parse application-specific files written by humans + (configuration files, resource files etc.) + + If $enable is false (the default), then "decode" will only accept + valid JSON texts. + + Currently accepted extensions are: + + * list items can have an end-comma + + JSON *separates* array elements and key-value pairs with + commas. This can be annoying if you write JSON texts manually + and want to be able to quickly append elements, so this + extension accepts comma at the end of such items not just + between them: + + [ + 1, + 2, <- this comma not normally allowed + ] + { + "k1": "v1", + "k2": "v2", <- this comma not normally allowed + } + + * shell-style '#'-comments + + Whenever JSON allows whitespace, shell-style comments are + additionally allowed. They are terminated by the first + carriage-return or line-feed character, after which more + white-space and comments are allowed. + + [ + 1, # this comment not allowed in JSON + # neither this one... + ] + + canonical + $json = $json->canonical([$enable]) + + $enabled = $json->get_canonical + + If $enable is true (or missing), then the "encode" method will + output JSON objects by sorting their keys. This is adding a + comparatively high overhead. + + If $enable is false, then the "encode" method will output + key-value pairs in the order Perl stores them (which will likely + change between runs of the same script, and can change even within + the same run from 5.18 onwards). + + This option is useful if you want the same data structure to be + encoded as the same JSON text (given the same overall settings). + If it is disabled, the same hash might be encoded differently even + if contains the same data, as key-value pairs have no inherent + ordering in Perl. + + This setting has no effect when decoding JSON texts. + + This setting has currently no effect on tied hashes. + + allow_nonref + $json = $json->allow_nonref([$enable]) + + $enabled = $json->get_allow_nonref + + If $enable is true (or missing), then the "encode" method can + convert a non-reference into its corresponding string, number or + null JSON value, which is an extension to RFC4627. Likewise, + "decode" will accept those JSON values instead of croaking. + + If $enable is false, then the "encode" method will croak if it + isn't passed an arrayref or hashref, as JSON texts must either be + an object or array. Likewise, "decode" will croak if given + something that is not a JSON object or array. + + Example, encode a Perl scalar as JSON value with enabled + "allow_nonref", resulting in an invalid JSON text: + + JSON->new->allow_nonref->encode ("Hello, World!") + => "Hello, World!" + + allow_unknown + $json = $json->allow_unknown ([$enable]) + + $enabled = $json->get_allow_unknown + + If $enable is true (or missing), then "encode" will *not* throw an + exception when it encounters values it cannot represent in JSON + (for example, filehandles) but instead will encode a JSON "null" + value. Note that blessed objects are not included here and are + handled separately by c<allow_nonref>. + + If $enable is false (the default), then "encode" will throw an + exception when it encounters anything it cannot encode as JSON. + + This option does not affect "decode" in any way, and it is + recommended to leave it off unless you know your communications + partner. + + allow_blessed + $json = $json->allow_blessed([$enable]) + + $enabled = $json->get_allow_blessed + + See "OBJECT SERIALISATION" for details. + + If $enable is true (or missing), then the "encode" method will not + barf when it encounters a blessed reference that it cannot convert + otherwise. Instead, a JSON "null" value is encoded instead of the + object. + + If $enable is false (the default), then "encode" will throw an + exception when it encounters a blessed object that it cannot + convert otherwise. + + This setting has no effect on "decode". + + convert_blessed + $json = $json->convert_blessed([$enable]) + + $enabled = $json->get_convert_blessed + + See "OBJECT SERIALISATION" for details. + + If $enable is true (or missing), then "encode", upon encountering + a blessed object, will check for the availability of the "TO_JSON" + method on the object's class. If found, it will be called in + scalar context and the resulting scalar will be encoded instead of + the object. + + The "TO_JSON" method may safely call die if it wants. If "TO_JSON" + returns other blessed objects, those will be handled in the same + way. "TO_JSON" must take care of not causing an endless recursion + cycle (== crash) in this case. The name of "TO_JSON" was chosen + because other methods called by the Perl core (== not by the user + of the object) are usually in upper case letters and to avoid + collisions with any "to_json" function or method. + + If $enable is false (the default), then "encode" will not consider + this type of conversion. + + This setting has no effect on "decode". + + filter_json_object + $json = $json->filter_json_object([$coderef]) + + When $coderef is specified, it will be called from "decode" each + time it decodes a JSON object. The only argument is a reference to + the newly-created hash. If the code references returns a single + scalar (which need not be a reference), this value (i.e. a copy of + that scalar to avoid aliasing) is inserted into the deserialised + data structure. If it returns an empty list (NOTE: *not* "undef", + which is a valid scalar), the original deserialised hash will be + inserted. This setting can slow down decoding considerably. + + When $coderef is omitted or undefined, any existing callback will + be removed and "decode" will not change the deserialised hash in + any way. + + Example, convert all JSON objects into the integer 5: + + my $js = JSON->new->filter_json_object (sub { 5 }); + # returns [5] + $js->decode ('[{}]'); # the given subroutine takes a hash reference. + # throw an exception because allow_nonref is not enabled + # so a lone 5 is not allowed. + $js->decode ('{"a":1, "b":2}'); + + filter_json_single_key_object + $json = $json->filter_json_single_key_object($key [=> $coderef]) + + Works remotely similar to "filter_json_object", but is only called + for JSON objects having a single key named $key. + + This $coderef is called before the one specified via + "filter_json_object", if any. It gets passed the single value in + the JSON object. If it returns a single value, it will be inserted + into the data structure. If it returns nothing (not even "undef" + but the empty list), the callback from "filter_json_object" will + be called next, as if no single-key callback were specified. + + If $coderef is omitted or undefined, the corresponding callback + will be disabled. There can only ever be one callback for a given + key. + + As this callback gets called less often then the + "filter_json_object" one, decoding speed will not usually suffer + as much. Therefore, single-key objects make excellent targets to + serialise Perl objects into, especially as single-key JSON objects + are as close to the type-tagged value concept as JSON gets (it's + basically an ID/VALUE tuple). Of course, JSON does not support + this in any way, so you need to make sure your data never looks + like a serialised Perl hash. + + Typical names for the single object key are "__class_whatever__", + or "$__dollars_are_rarely_used__$" or "}ugly_brace_placement", or + even things like "__class_md5sum(classname)__", to reduce the risk + of clashing with real hashes. + + Example, decode JSON objects of the form "{ "__widget__" => <id> + }" into the corresponding $WIDGET{<id>} object: + + # return whatever is in $WIDGET{5}: + JSON + ->new + ->filter_json_single_key_object (__widget__ => sub { + $WIDGET{ $_[0] } + }) + ->decode ('{"__widget__": 5') + + # this can be used with a TO_JSON method in some "widget" class + # for serialisation to json: + sub WidgetBase::TO_JSON { + my ($self) = @_; + + unless ($self->{id}) { + $self->{id} = ..get..some..id..; + $WIDGET{$self->{id}} = $self; + } + + { __widget__ => $self->{id} } + } + + max_depth + $json = $json->max_depth([$maximum_nesting_depth]) + + $max_depth = $json->get_max_depth + + Sets the maximum nesting level (default 512) accepted while + encoding or decoding. If a higher nesting level is detected in + JSON text or a Perl data structure, then the encoder and decoder + will stop and croak at that point. + + Nesting level is defined by number of hash- or arrayrefs that the + encoder needs to traverse to reach a given point or the number of + "{" or "[" characters without their matching closing parenthesis + crossed to reach a given character in a string. + + Setting the maximum depth to one disallows any nesting, so that + ensures that the object is only a single hash/object or array. + + If no argument is given, the highest possible setting will be + used, which is rarely useful. + + max_size + $json = $json->max_size([$maximum_string_size]) + + $max_size = $json->get_max_size + + Set the maximum length a JSON text may have (in bytes) where + decoding is being attempted. The default is 0, meaning no limit. + When "decode" is called on a string that is longer then this many + bytes, it will not attempt to decode the string but throw an + exception. This setting has no effect on "encode" (yet). + + If no argument is given, the limit check will be deactivated (same + as when 0 is specified). + + encode + $json_text = $json->encode($perl_scalar) + + Converts the given Perl value or data structure to its JSON + representation. Croaks on error. + + decode + $perl_scalar = $json->decode($json_text) + + The opposite of "encode": expects a JSON text and tries to parse + it, returning the resulting simple scalar or reference. Croaks on + error. + + decode_prefix + ($perl_scalar, $characters) = $json->decode_prefix($json_text) + + This works like the "decode" method, but instead of raising an + exception when there is trailing garbage after the first JSON + object, it will silently stop parsing there and return the number + of characters consumed so far. + + This is useful if your JSON texts are not delimited by an outer + protocol and you need to know where the JSON text ends. + + JSON->new->decode_prefix ("[1] the tail") + => ([1], 3) + +ADDITIONAL METHODS + The following methods are for this module only. + + backend + $backend = $json->backend + + Since 2.92, "backend" method returns an abstract backend module + used currently, which should be JSON::Backend::XS (which inherits + JSON::XS or Cpanel::JSON::XS), or JSON::Backend::PP (which + inherits JSON::PP), not to monkey-patch the actual backend module + globally. + + If you need to know what is used actually, use "isa", instead of + string comparison. + + is_xs + $boolean = $json->is_xs + + Returns true if the backend inherits JSON::XS or Cpanel::JSON::XS. + + is_pp + $boolean = $json->is_pp + + Returns true if the backend inherits JSON::PP. + + property + $settings = $json->property() + + Returns a reference to a hash that holds all the common flag + settings. + + $json = $json->property('utf8' => 1) + $value = $json->property('utf8') # 1 + + You can use this to get/set a value of a particular flag. + +INCREMENTAL PARSING + This section is also taken from JSON::XS. + + In some cases, there is the need for incremental parsing of JSON + texts. While this module always has to keep both JSON text and + resulting Perl data structure in memory at one time, it does allow + you to parse a JSON stream incrementally. It does so by + accumulating text until it has a full JSON object, which it then + can decode. This process is similar to using "decode_prefix" to + see if a full JSON object is available, but is much more efficient + (and can be implemented with a minimum of method calls). + + This module will only attempt to parse the JSON text once it is + sure it has enough text to get a decisive result, using a very + simple but truly incremental parser. This means that it sometimes + won't stop as early as the full parser, for example, it doesn't + detect mismatched parentheses. The only thing it guarantees is + that it starts decoding as soon as a syntactically valid JSON text + has been seen. This means you need to set resource limits (e.g. + "max_size") to ensure the parser will stop parsing in the presence + if syntax errors. + + The following methods implement this incremental parser. + + incr_parse + $json->incr_parse( [$string] ) # void context + + $obj_or_undef = $json->incr_parse( [$string] ) # scalar context + + @obj_or_empty = $json->incr_parse( [$string] ) # list context + + This is the central parsing function. It can both append new text + and extract objects from the stream accumulated so far (both of + these functions are optional). + + If $string is given, then this string is appended to the already + existing JSON fragment stored in the $json object. + + After that, if the function is called in void context, it will + simply return without doing anything further. This can be used to + add more text in as many chunks as you want. + + If the method is called in scalar context, then it will try to + extract exactly *one* JSON object. If that is successful, it will + return this object, otherwise it will return "undef". If there is + a parse error, this method will croak just as "decode" would do + (one can then use "incr_skip" to skip the erroneous part). This is + the most common way of using the method. + + And finally, in list context, it will try to extract as many + objects from the stream as it can find and return them, or the + empty list otherwise. For this to work, there must be no + separators (other than whitespace) between the JSON objects or + arrays, instead they must be concatenated back-to-back. If an + error occurs, an exception will be raised as in the scalar context + case. Note that in this case, any previously-parsed JSON texts + will be lost. + + Example: Parse some JSON arrays/objects in a given string and + return them. + + my @objs = JSON->new->incr_parse ("[5][7][1,2]"); + + incr_text + $lvalue_string = $json->incr_text + + This method returns the currently stored JSON fragment as an + lvalue, that is, you can manipulate it. This *only* works when a + preceding call to "incr_parse" in *scalar context* successfully + returned an object. Under all other circumstances you must not + call this function (I mean it. although in simple tests it might + actually work, it *will* fail under real world conditions). As a + special exception, you can also call this method before having + parsed anything. + + That means you can only use this function to look at or manipulate + text before or after complete JSON objects, not while the parser + is in the middle of parsing a JSON object. + + This function is useful in two cases: a) finding the trailing text + after a JSON object or b) parsing multiple JSON objects separated + by non-JSON text (such as commas). + + incr_skip + $json->incr_skip + + This will reset the state of the incremental parser and will + remove the parsed text from the input buffer so far. This is + useful after "incr_parse" died, in which case the input buffer and + incremental parser state is left unchanged, to skip the text + parsed so far and to reset the parse state. + + The difference to "incr_reset" is that only text until the parse + error occurred is removed. + + incr_reset + $json->incr_reset + + This completely resets the incremental parser, that is, after this + call, it will be as if the parser had never parsed anything. + + This is useful if you want to repeatedly parse JSON objects and + want to ignore any trailing data, which means you have to reset + the parser after each successful decode. + +MAPPING + Most of this section is also taken from JSON::XS. + + This section describes how the backend modules map Perl values to + JSON values and vice versa. These mappings are designed to "do the + right thing" in most circumstances automatically, preserving + round-tripping characteristics (what you put in comes out as + something equivalent). + + For the more enlightened: note that in the following descriptions, + lowercase *perl* refers to the Perl interpreter, while uppercase + *Perl* refers to the abstract Perl language itself. + + JSON -> PERL + object + A JSON object becomes a reference to a hash in Perl. No + ordering of object keys is preserved (JSON does not preserver + object key ordering itself). + + array + A JSON array becomes a reference to an array in Perl. + + string + A JSON string becomes a string scalar in Perl - Unicode + codepoints in JSON are represented by the same codepoints in + the Perl string, so no manual decoding is necessary. + + number + A JSON number becomes either an integer, numeric (floating + point) or string scalar in perl, depending on its range and + any fractional parts. On the Perl level, there is no + difference between those as Perl handles all the conversion + details, but an integer may take slightly less memory and + might represent more values exactly than floating point + numbers. + + If the number consists of digits only, this module will try to + represent it as an integer value. If that fails, it will try + to represent it as a numeric (floating point) value if that is + possible without loss of precision. Otherwise it will preserve + the number as a string value (in which case you lose + roundtripping ability, as the JSON number will be re-encoded + to a JSON string). + + Numbers containing a fractional or exponential part will + always be represented as numeric (floating point) values, + possibly at a loss of precision (in which case you might lose + perfect roundtripping ability, but the JSON number will still + be re-encoded as a JSON number). + + Note that precision is not accuracy - binary floating point + values cannot represent most decimal fractions exactly, and + when converting from and to floating point, this module only + guarantees precision up to but not including the least + significant bit. + + true, false + These JSON atoms become "JSON::true" and "JSON::false", + respectively. They are overloaded to act almost exactly like + the numbers 1 and 0. You can check whether a scalar is a JSON + boolean by using the "JSON::is_bool" function. + + null + A JSON null atom becomes "undef" in Perl. + + shell-style comments ("# *text*") + As a nonstandard extension to the JSON syntax that is enabled + by the "relaxed" setting, shell-style comments are allowed. + They can start anywhere outside strings and go till the end of + the line. + + PERL -> JSON + The mapping from Perl to JSON is slightly more difficult, as Perl + is a truly typeless language, so we can only guess which JSON type + is meant by a Perl value. + + hash references + Perl hash references become JSON objects. As there is no + inherent ordering in hash keys (or JSON objects), they will + usually be encoded in a pseudo-random order. This module can + optionally sort the hash keys (determined by the *canonical* + flag), so the same data structure will serialise to the same + JSON text (given same settings and version of the same + backend), but this incurs a runtime overhead and is only + rarely useful, e.g. when you want to compare some JSON text + against another for equality. + + array references + Perl array references become JSON arrays. + + other references + Other unblessed references are generally not allowed and will + cause an exception to be thrown, except for references to the + integers 0 and 1, which get turned into "false" and "true" + atoms in JSON. You can also use "JSON::false" and "JSON::true" + to improve readability. + + encode_json [\0,JSON::true] # yields [false,true] + + JSON::true, JSON::false, JSON::null + These special values become JSON true and JSON false values, + respectively. You can also use "\1" and "\0" directly if you + want. + + blessed objects + Blessed objects are not directly representable in JSON, but + "JSON::XS" allows various ways of handling objects. See + "OBJECT SERIALISATION", below, for details. + + simple scalars + Simple Perl scalars (any scalar that is not a reference) are + the most difficult objects to encode: this module will encode + undefined scalars as JSON "null" values, scalars that have + last been used in a string context before encoding as JSON + strings, and anything else as number value: + + # dump as number + encode_json [2] # yields [2] + encode_json [-3.0e17] # yields [-3e+17] + my $value = 5; encode_json [$value] # yields [5] + + # used as string, so dump as string + print $value; + encode_json [$value] # yields ["5"] + + # undef becomes null + encode_json [undef] # yields [null] + + You can force the type to be a string by stringifying it: + + my $x = 3.1; # some variable containing a number + "$x"; # stringified + $x .= ""; # another, more awkward way to stringify + print $x; # perl does it for you, too, quite often + + You can force the type to be a number by numifying it: + + my $x = "3"; # some variable containing a string + $x += 0; # numify it, ensuring it will be dumped as a number + $x *= 1; # same thing, the choice is yours. + + You can not currently force the type in other, less obscure, + ways. Tell me if you need this capability (but don't forget to + explain why it's needed :). + + Note that numerical precision has the same meaning as under + Perl (so binary to decimal conversion follows the same rules + as in Perl, which can differ to other languages). Also, your + perl interpreter might expose extensions to the floating point + numbers of your platform, such as infinities or NaN's - these + cannot be represented in JSON, and it is an error to pass + those in. + + OBJECT SERIALISATION + As for Perl objects, this module only supports a pure JSON + representation (without the ability to deserialise the object + automatically again). + + SERIALISATION + What happens when this module encounters a Perl object depends on + the "allow_blessed" and "convert_blessed" settings, which are used + in this order: + + 1. "convert_blessed" is enabled and the object has a "TO_JSON" + method. + In this case, the "TO_JSON" method of the object is invoked in + scalar context. It must return a single scalar that can be + directly encoded into JSON. This scalar replaces the object in + the JSON text. + + For example, the following "TO_JSON" method will convert all + URI objects to JSON strings when serialised. The fact that + these values originally were URI objects is lost. + + sub URI::TO_JSON { + my ($uri) = @_; + $uri->as_string + } + + 2. "allow_blessed" is enabled. + The object will be serialised as a JSON null value. + + 3. none of the above + If none of the settings are enabled or the respective methods + are missing, this module throws an exception. + +ENCODING/CODESET FLAG NOTES + This section is taken from JSON::XS. + + The interested reader might have seen a number of flags that + signify encodings or codesets - "utf8", "latin1" and "ascii". + There seems to be some confusion on what these do, so here is a + short comparison: + + "utf8" controls whether the JSON text created by "encode" (and + expected by "decode") is UTF-8 encoded or not, while "latin1" and + "ascii" only control whether "encode" escapes character values + outside their respective codeset range. Neither of these flags + conflict with each other, although some combinations make less + sense than others. + + Care has been taken to make all flags symmetrical with respect to + "encode" and "decode", that is, texts encoded with any combination + of these flag values will be correctly decoded when the same flags + are used - in general, if you use different flag settings while + encoding vs. when decoding you likely have a bug somewhere. + + Below comes a verbose discussion of these flags. Note that a + "codeset" is simply an abstract set of character-codepoint pairs, + while an encoding takes those codepoint numbers and *encodes* + them, in our case into octets. Unicode is (among other things) a + codeset, UTF-8 is an encoding, and ISO-8859-1 (= latin 1) and + ASCII are both codesets *and* encodings at the same time, which + can be confusing. + + "utf8" flag disabled + When "utf8" is disabled (the default), then "encode"/"decode" + generate and expect Unicode strings, that is, characters with + high ordinal Unicode values (> 255) will be encoded as such + characters, and likewise such characters are decoded as-is, no + changes to them will be done, except "(re-)interpreting" them + as Unicode codepoints or Unicode characters, respectively (to + Perl, these are the same thing in strings unless you do + funny/weird/dumb stuff). + + This is useful when you want to do the encoding yourself (e.g. + when you want to have UTF-16 encoded JSON texts) or when some + other layer does the encoding for you (for example, when + printing to a terminal using a filehandle that transparently + encodes to UTF-8 you certainly do NOT want to UTF-8 encode + your data first and have Perl encode it another time). + + "utf8" flag enabled + If the "utf8"-flag is enabled, "encode"/"decode" will encode + all characters using the corresponding UTF-8 multi-byte + sequence, and will expect your input strings to be encoded as + UTF-8, that is, no "character" of the input string must have + any value > 255, as UTF-8 does not allow that. + + The "utf8" flag therefore switches between two modes: disabled + means you will get a Unicode string in Perl, enabled means you + get an UTF-8 encoded octet/binary string in Perl. + + "latin1" or "ascii" flags enabled + With "latin1" (or "ascii") enabled, "encode" will escape + characters with ordinal values > 255 (> 127 with "ascii") and + encode the remaining characters as specified by the "utf8" + flag. + + If "utf8" is disabled, then the result is also correctly + encoded in those character sets (as both are proper subsets of + Unicode, meaning that a Unicode string with all character + values < 256 is the same thing as a ISO-8859-1 string, and a + Unicode string with all character values < 128 is the same + thing as an ASCII string in Perl). + + If "utf8" is enabled, you still get a correct UTF-8-encoded + string, regardless of these flags, just some more characters + will be escaped using "\uXXXX" then before. + + Note that ISO-8859-1-*encoded* strings are not compatible with + UTF-8 encoding, while ASCII-encoded strings are. That is + because the ISO-8859-1 encoding is NOT a subset of UTF-8 + (despite the ISO-8859-1 *codeset* being a subset of Unicode), + while ASCII is. + + Surprisingly, "decode" will ignore these flags and so treat + all input values as governed by the "utf8" flag. If it is + disabled, this allows you to decode ISO-8859-1- and + ASCII-encoded strings, as both strict subsets of Unicode. If + it is enabled, you can correctly decode UTF-8 encoded strings. + + So neither "latin1" nor "ascii" are incompatible with the + "utf8" flag - they only govern when the JSON output engine + escapes a character or not. + + The main use for "latin1" is to relatively efficiently store + binary data as JSON, at the expense of breaking compatibility + with most JSON decoders. + + The main use for "ascii" is to force the output to not contain + characters with values > 127, which means you can interpret + the resulting string as UTF-8, ISO-8859-1, ASCII, KOI8-R or + most about any character set and 8-bit-encoding, and still get + the same data structure back. This is useful when your channel + for JSON transfer is not 8-bit clean or the encoding might be + mangled in between (e.g. in mail), and works because ASCII is + a proper subset of most 8-bit and multibyte encodings in use + in the world. + +BACKWARD INCOMPATIBILITY + Since version 2.90, stringification (and string comparison) for + "JSON::true" and "JSON::false" has not been overloaded. It + shouldn't matter as long as you treat them as boolean values, but + a code that expects they are stringified as "true" or "false" + doesn't work as you have expected any more. + + if (JSON::true eq 'true') { # now fails + + print "The result is $JSON::true now."; # => The result is 1 now. + + And now these boolean values don't inherit JSON::Boolean, either. + When you need to test a value is a JSON boolean value or not, use + "JSON::is_bool" function, instead of testing the value inherits a + particular boolean class or not. + +BUGS + Please report bugs on backend selection and additional features + this module provides to RT or GitHub issues for this module: + + https://rt.cpan.org/Public/Dist/Display.html?Queue=JSON + https://github.com/makamaka/JSON/issues + + Please report bugs and feature requests on decoding/encoding and + boolean behaviors to the author of the backend module you are + using. + +SEE ALSO + JSON::XS, Cpanel::JSON::XS, JSON::PP for backends. + + JSON::MaybeXS, an alternative that prefers Cpanel::JSON::XS. + + "RFC4627"(<http://www.ietf.org/rfc/rfc4627.txt>) + +AUTHOR + Makamaka Hannyaharamitu, <makamaka[at]cpan.org> + + JSON::XS was written by Marc Lehmann <schmorp[at]schmorp.de> + + The release of this new version owes to the courtesy of Marc + Lehmann. + +COPYRIGHT AND LICENSE + Copyright 2005-2013 by Makamaka Hannyaharamitu + + This library is free software; you can redistribute it and/or + modify it under the same terms as Perl itself. + diff --git a/eg/bench_decode.pl b/eg/bench_decode.pl new file mode 100644 index 0000000..097655f --- /dev/null +++ b/eg/bench_decode.pl @@ -0,0 +1,68 @@ +use strict; +use warnings; +use Benchmark qw( cmpthese timethese ); + +our $VERSION = '1.00'; + +my $wanttime = $ARGV[1] || 5; + +use JSON qw( -support_by_pp -no_export ); # for JSON::PP::Boolean inheritance +use JSON::PP (); +use JSON::XS (); +use utf8; + +my $pp = JSON::PP->new->utf8; +my $xs = JSON::XS->new->utf8; + +local $/; + +my $json = <>; +my $perl = JSON::XS::decode_json $json; +my $result; + + +printf( "JSON::PP %s\n", JSON::PP->VERSION ); +printf( "JSON::XS %s\n", JSON::XS->VERSION ); + + +print "-----------------------------------\n"; +print "->decode()\n"; +print "-----------------------------------\n"; + +$result = timethese( -$wanttime, + { + 'JSON::PP' => sub { $pp->decode( $json ) }, + 'JSON::XS' => sub { $xs->decode( $json ) }, + }, + 'none' +); +cmpthese( $result ); + +print "-----------------------------------\n"; + + +__END__ + +=pod + +=head1 SYNOPSYS + + bench_decode.pl json-file + # or + bench_decode.pl json-file minimum-time + +=head1 DESCRIPTION + +L<JSON::PP> and L<JSON::XS> decoding benchmark. + +=head1 AUTHOR + +makamaka + +=head1 LISENCE + +This library is free software; you can redistribute it and/or modify it +under the same terms as Perl itself. + +=cut + diff --git a/eg/bench_encode.pl b/eg/bench_encode.pl new file mode 100644 index 0000000..0df914c --- /dev/null +++ b/eg/bench_encode.pl @@ -0,0 +1,84 @@ +use strict; +use warnings; +use Benchmark qw( cmpthese timethese ); + +our $VERSION = '1.00'; + +my $wanttime = $ARGV[1] || 5; + +use JSON qw( -support_by_pp -no_export ); # for JSON::PP::Boolean inheritance +use JSON::PP (); +use JSON::XS (); +use utf8; + +my $pp = JSON::PP->new->utf8; +my $xs = JSON::XS->new->utf8; + +local $/; + +my $json = <>; +my $perl = JSON::XS::decode_json $json; +my $result; + + +printf( "JSON::PP %s\n", JSON::PP->VERSION ); +printf( "JSON::XS %s\n", JSON::XS->VERSION ); + + +print "-----------------------------------\n"; +print "->encode()\n"; +print "-----------------------------------\n"; + +$result = timethese( -$wanttime, + { + 'JSON::PP' => sub { $pp->encode( $perl ) }, + 'JSON::XS' => sub { $xs->encode( $perl ) }, + }, + 'none' +); +cmpthese( $result ); + +print "-----------------------------------\n"; +print "->pretty->canonical->encode()\n"; +print "-----------------------------------\n"; + +$pp->pretty->canonical; +$xs->pretty->canonical; + +$result = timethese( -$wanttime, + { + 'JSON::PP' => sub { $pp->encode( $perl ) }, + 'JSON::XS' => sub { $xs->encode( $perl ) }, + }, + 'none' +); +cmpthese( $result ); + +print "-----------------------------------\n"; + + +__END__ + +=pod + +=head1 SYNOPSYS + + bench_encode.pl json-file + # or + bench_encode.pl json-file minimum-time + +=head1 DESCRIPTION + +L<JSON::PP> and L<JSON::XS> encoding benchmark. + +=head1 AUTHOR + +makamaka + +=head1 LISENCE + +This library is free software; you can redistribute it and/or modify it +under the same terms as Perl itself. + +=cut + diff --git a/lib/JSON.pm b/lib/JSON.pm new file mode 100644 index 0000000..d58fc6a --- /dev/null +++ b/lib/JSON.pm @@ -0,0 +1,1848 @@ +package JSON; + + +use strict; +use Carp (); +use Exporter; +BEGIN { @JSON::ISA = 'Exporter' } + +@JSON::EXPORT = qw(from_json to_json jsonToObj objToJson encode_json decode_json); + +BEGIN { + $JSON::VERSION = '4.02'; + $JSON::DEBUG = 0 unless (defined $JSON::DEBUG); + $JSON::DEBUG = $ENV{ PERL_JSON_DEBUG } if exists $ENV{ PERL_JSON_DEBUG }; +} + +my %RequiredVersion = ( + 'JSON::PP' => '2.27203', + 'JSON::XS' => '2.34', +); + +# XS and PP common methods + +my @PublicMethods = qw/ + ascii latin1 utf8 pretty indent space_before space_after relaxed canonical allow_nonref + allow_blessed convert_blessed filter_json_object filter_json_single_key_object + shrink max_depth max_size encode decode decode_prefix allow_unknown +/; + +my @Properties = qw/ + ascii latin1 utf8 indent space_before space_after relaxed canonical allow_nonref + allow_blessed convert_blessed shrink max_depth max_size allow_unknown +/; + +my @XSOnlyMethods = qw//; # Currently nothing + +my @PublicMethodsSince4_0 = qw/allow_tags/; +my @PropertiesSince4_0 = qw/allow_tags/; + +my @PPOnlyMethods = qw/ + indent_length sort_by + allow_singlequote allow_bignum loose allow_barekey escape_slash as_nonblessed +/; # JSON::PP specific + + +# used in _load_xs and _load_pp ($INSTALL_ONLY is not used currently) +my $_INSTALL_DONT_DIE = 1; # When _load_xs fails to load XS, don't die. +my $_ALLOW_UNSUPPORTED = 0; +my $_UNIV_CONV_BLESSED = 0; + + +# Check the environment variable to decide worker module. + +unless ($JSON::Backend) { + $JSON::DEBUG and Carp::carp("Check used worker module..."); + + my $backend = exists $ENV{PERL_JSON_BACKEND} ? $ENV{PERL_JSON_BACKEND} : 1; + + if ($backend eq '1') { + $backend = 'JSON::XS,JSON::PP'; + } + elsif ($backend eq '0') { + $backend = 'JSON::PP'; + } + elsif ($backend eq '2') { + $backend = 'JSON::XS'; + } + $backend =~ s/\s+//g; + + my @backend_modules = split /,/, $backend; + while(my $module = shift @backend_modules) { + if ($module =~ /JSON::XS/) { + _load_xs($module, @backend_modules ? $_INSTALL_DONT_DIE : 0); + } + elsif ($module =~ /JSON::PP/) { + _load_pp($module); + } + elsif ($module =~ /JSON::backportPP/) { + _load_pp($module); + } + else { + Carp::croak "The value of environmental variable 'PERL_JSON_BACKEND' is invalid."; + } + last if $JSON::Backend; + } +} + + +sub import { + my $pkg = shift; + my @what_to_export; + my $no_export; + + for my $tag (@_) { + if ($tag eq '-support_by_pp') { + if (!$_ALLOW_UNSUPPORTED++) { + JSON::Backend::XS + ->support_by_pp(@PPOnlyMethods) if ($JSON::Backend->is_xs); + } + next; + } + elsif ($tag eq '-no_export') { + $no_export++, next; + } + elsif ( $tag eq '-convert_blessed_universally' ) { + my $org_encode = $JSON::Backend->can('encode'); + eval q| + require B; + local $^W; + no strict 'refs'; + *{"${JSON::Backend}\::encode"} = sub { + # only works with Perl 5.18+ + local *UNIVERSAL::TO_JSON = sub { + my $b_obj = B::svref_2object( $_[0] ); + return $b_obj->isa('B::HV') ? { %{ $_[0] } } + : $b_obj->isa('B::AV') ? [ @{ $_[0] } ] + : undef + ; + }; + $org_encode->(@_); + }; + | if ( !$_UNIV_CONV_BLESSED++ ); + next; + } + push @what_to_export, $tag; + } + + return if ($no_export); + + __PACKAGE__->export_to_level(1, $pkg, @what_to_export); +} + + +# OBSOLETED + +sub jsonToObj { + my $alternative = 'from_json'; + if (defined $_[0] and UNIVERSAL::isa($_[0], 'JSON')) { + shift @_; $alternative = 'decode'; + } + Carp::carp "'jsonToObj' will be obsoleted. Please use '$alternative' instead."; + return JSON::from_json(@_); +}; + +sub objToJson { + my $alternative = 'to_json'; + if (defined $_[0] and UNIVERSAL::isa($_[0], 'JSON')) { + shift @_; $alternative = 'encode'; + } + Carp::carp "'objToJson' will be obsoleted. Please use '$alternative' instead."; + JSON::to_json(@_); +}; + + +# INTERFACES + +sub to_json ($@) { + if ( + ref($_[0]) eq 'JSON' + or (@_ > 2 and $_[0] eq 'JSON') + ) { + Carp::croak "to_json should not be called as a method."; + } + my $json = JSON->new; + + if (@_ == 2 and ref $_[1] eq 'HASH') { + my $opt = $_[1]; + for my $method (keys %$opt) { + $json->$method( $opt->{$method} ); + } + } + + $json->encode($_[0]); +} + + +sub from_json ($@) { + if ( ref($_[0]) eq 'JSON' or $_[0] eq 'JSON' ) { + Carp::croak "from_json should not be called as a method."; + } + my $json = JSON->new; + + if (@_ == 2 and ref $_[1] eq 'HASH') { + my $opt = $_[1]; + for my $method (keys %$opt) { + $json->$method( $opt->{$method} ); + } + } + + return $json->decode( $_[0] ); +} + + + +sub true { $JSON::true } + +sub false { $JSON::false } + +sub boolean { + # might be called as method or as function, so pop() to get the last arg instead of shift() to get the first + pop() ? $JSON::true : $JSON::false +} + +sub null { undef; } + + +sub require_xs_version { $RequiredVersion{'JSON::XS'}; } + +sub backend { + my $proto = shift; + $JSON::Backend; +} + +#*module = *backend; + + +sub is_xs { + return $_[0]->backend->is_xs; +} + + +sub is_pp { + return $_[0]->backend->is_pp; +} + + +sub pureperl_only_methods { @PPOnlyMethods; } + + +sub property { + my ($self, $name, $value) = @_; + + if (@_ == 1) { + my %props; + for $name (@Properties) { + my $method = 'get_' . $name; + if ($name eq 'max_size') { + my $value = $self->$method(); + $props{$name} = $value == 1 ? 0 : $value; + next; + } + $props{$name} = $self->$method(); + } + return \%props; + } + elsif (@_ > 3) { + Carp::croak('property() can take only the option within 2 arguments.'); + } + elsif (@_ == 2) { + if ( my $method = $self->can('get_' . $name) ) { + if ($name eq 'max_size') { + my $value = $self->$method(); + return $value == 1 ? 0 : $value; + } + $self->$method(); + } + } + else { + $self->$name($value); + } + +} + + + +# INTERNAL + +sub __load_xs { + my ($module, $opt) = @_; + + $JSON::DEBUG and Carp::carp "Load $module."; + my $required_version = $RequiredVersion{$module} || ''; + + eval qq| + use $module $required_version (); + |; + + if ($@) { + if (defined $opt and $opt & $_INSTALL_DONT_DIE) { + $JSON::DEBUG and Carp::carp "Can't load $module...($@)"; + return 0; + } + Carp::croak $@; + } + $JSON::BackendModuleXS = $module; + return 1; +} + +sub _load_xs { + my ($module, $opt) = @_; + __load_xs($module, $opt) or return; + + my $data = join("", <DATA>); # this code is from Jcode 2.xx. + close(DATA); + eval $data; + JSON::Backend::XS->init($module); + + return 1; +}; + + +sub __load_pp { + my ($module, $opt) = @_; + + $JSON::DEBUG and Carp::carp "Load $module."; + my $required_version = $RequiredVersion{$module} || ''; + + eval qq| use $module $required_version () |; + + if ($@) { + if ( $module eq 'JSON::PP' ) { + $JSON::DEBUG and Carp::carp "Can't load $module ($@), so try to load JSON::backportPP"; + $module = 'JSON::backportPP'; + local $^W; # if PP installed but invalid version, backportPP redefines methods. + eval qq| require $module |; + } + Carp::croak $@ if $@; + } + $JSON::BackendModulePP = $module; + return 1; +} + +sub _load_pp { + my ($module, $opt) = @_; + __load_pp($module, $opt); + + JSON::Backend::PP->init($module); +}; + +# +# Helper classes for Backend Module (PP) +# + +package JSON::Backend::PP; + +sub init { + my ($class, $module) = @_; + + # name may vary, but the module should (always) be a JSON::PP + + local $^W; + no strict qw(refs); # this routine may be called after JSON::Backend::XS init was called. + *{"JSON::decode_json"} = \&{"JSON::PP::decode_json"}; + *{"JSON::encode_json"} = \&{"JSON::PP::encode_json"}; + *{"JSON::is_bool"} = \&{"JSON::PP::is_bool"}; + + $JSON::true = ${"JSON::PP::true"}; + $JSON::false = ${"JSON::PP::false"}; + + push @JSON::Backend::PP::ISA, 'JSON::PP'; + push @JSON::ISA, $class; + $JSON::Backend = $class; + $JSON::BackendModule = $module; + my $version = ${"$class\::VERSION"} = $module->VERSION; + $version =~ s/_//; + if ($version < 3.99) { + push @XSOnlyMethods, qw/allow_tags get_allow_tags/; + } else { + push @Properties, 'allow_tags'; + } + + for my $method (@XSOnlyMethods) { + *{"JSON::$method"} = sub { + Carp::carp("$method is not supported by $module $version."); + $_[0]; + }; + } + + return 1; +} + +sub is_xs { 0 }; +sub is_pp { 1 }; + +# +# To save memory, the below lines are read only when XS backend is used. +# + +package JSON; + +1; +__DATA__ + + +# +# Helper classes for Backend Module (XS) +# + +package JSON::Backend::XS; + +sub init { + my ($class, $module) = @_; + + local $^W; + no strict qw(refs); + *{"JSON::decode_json"} = \&{"$module\::decode_json"}; + *{"JSON::encode_json"} = \&{"$module\::encode_json"}; + *{"JSON::is_bool"} = \&{"$module\::is_bool"}; + + $JSON::true = ${"$module\::true"}; + $JSON::false = ${"$module\::false"}; + + push @JSON::Backend::XS::ISA, $module; + push @JSON::ISA, $class; + $JSON::Backend = $class; + $JSON::BackendModule = $module; + ${"$class\::VERSION"} = $module->VERSION; + + if ( $module->VERSION < 3 ) { + eval 'package JSON::PP::Boolean'; + push @{"$module\::Boolean::ISA"}, qw(JSON::PP::Boolean); + } + + for my $method (@PPOnlyMethods) { + *{"JSON::$method"} = sub { + Carp::carp("$method is not supported by $module."); + $_[0]; + }; + } + + return 1; +} + +sub is_xs { 1 }; +sub is_pp { 0 }; + +sub support_by_pp { + my ($class, @methods) = @_; + + JSON::__load_pp('JSON::PP'); + + local $^W; + no strict qw(refs); + + for my $method (@methods) { + my $pp_method = JSON::PP->can($method) or next; + *{"JSON::$method"} = sub { + if (!$_[0]->isa('JSON::PP')) { + my $xs_self = $_[0]; + my $pp_self = JSON::PP->new; + for (@Properties) { + my $getter = "get_$_"; + $pp_self->$_($xs_self->$getter); + } + $_[0] = $pp_self; + } + $pp_method->(@_); + }; + } + + $JSON::DEBUG and Carp::carp("set -support_by_pp mode."); +} + +1; +__END__ + +=head1 NAME + +JSON - JSON (JavaScript Object Notation) encoder/decoder + +=head1 SYNOPSIS + + use JSON; # imports encode_json, decode_json, to_json and from_json. + + # simple and fast interfaces (expect/generate UTF-8) + + $utf8_encoded_json_text = encode_json $perl_hash_or_arrayref; + $perl_hash_or_arrayref = decode_json $utf8_encoded_json_text; + + # OO-interface + + $json = JSON->new->allow_nonref; + + $json_text = $json->encode( $perl_scalar ); + $perl_scalar = $json->decode( $json_text ); + + $pretty_printed = $json->pretty->encode( $perl_scalar ); # pretty-printing + +=head1 VERSION + + 4.02 + +=head1 DESCRIPTION + +This module is a thin wrapper for L<JSON::XS>-compatible modules with a few +additional features. All the backend modules convert a Perl data structure +to a JSON text and vice versa. This module uses L<JSON::XS> by default, +and when JSON::XS is not available, falls back on L<JSON::PP>, which is +in the Perl core since 5.14. If JSON::PP is not available either, this +module then falls back on JSON::backportPP (which is actually JSON::PP +in a different .pm file) bundled in the same distribution as this module. +You can also explicitly specify to use L<Cpanel::JSON::XS>, a fork of +JSON::XS by Reini Urban. + +All these backend modules have slight incompatibilities between them, +including extra features that other modules don't support, but as long as you +use only common features (most important ones are described below), migration +from backend to backend should be reasonably easy. For details, see each +backend module you use. + +=head1 CHOOSING BACKEND + +This module respects an environmental variable called C<PERL_JSON_BACKEND> +when it decides a backend module to use. If this environmental variable is +not set, it tries to load JSON::XS, and if JSON::XS is not available, it +falls back on JSON::PP, and then JSON::backportPP if JSON::PP is not available +either. + +If you always don't want it to fall back on pure perl modules, set the +variable like this (C<export> may be C<setenv>, C<set> and the likes, +depending on your environment): + + > export PERL_JSON_BACKEND=JSON::XS + +If you prefer Cpanel::JSON::XS to JSON::XS, then: + + > export PERL_JSON_BACKEND=Cpanel::JSON::XS,JSON::XS,JSON::PP + +You may also want to set this variable at the top of your test files, in order +not to be bothered with incompatibilities between backends (you need to wrap +this in C<BEGIN>, and set before actually C<use>-ing JSON module, as it decides +its backend as soon as it's loaded): + + BEGIN { $ENV{PERL_JSON_BACKEND}='JSON::backportPP'; } + use JSON; + +=head1 USING OPTIONAL FEATURES + +There are a few options you can set when you C<use> this module. +These historical options are only kept for backward compatibility, +and should not be used in a new application. + +=over + +=item -support_by_pp + + BEGIN { $ENV{PERL_JSON_BACKEND} = 'JSON::XS' } + + use JSON -support_by_pp; + + my $json = JSON->new; + # escape_slash is for JSON::PP only. + $json->allow_nonref->escape_slash->encode("/"); + +With this option, this module loads its pure perl backend along with +its XS backend (if available), and lets the XS backend to watch if you set +a flag only JSON::PP supports. When you do, the internal JSON::XS object +is replaced with a newly created JSON::PP object with the setting copied +from the XS object, so that you can use JSON::PP flags (and its slower +C<decode>/C<encode> methods) from then on. In other words, this is not +something that allows you to hook JSON::XS to change its behavior while +keeping its speed. JSON::XS and JSON::PP objects are quite different +(JSON::XS object is a blessed scalar reference, while JSON::PP object is +a blessed hash reference), and can't share their internals. + +To avoid needless overhead (by copying settings), you are advised not +to use this option and just to use JSON::PP explicitly when you need +JSON::PP features. + +=item -convert_blessed_universally + + use JSON -convert_blessed_universally; + + my $json = JSON->new->allow_nonref->convert_blessed; + my $object = bless {foo => 'bar'}, 'Foo'; + $json->encode($object); # => {"foo":"bar"} + +JSON::XS-compatible backend modules don't encode blessed objects by +default (except for their boolean values, which are typically blessed +JSON::PP::Boolean objects). If you need to encode a data structure +that may contain objects, you usually need to look into the structure +and replace objects with alternative non-blessed values, or enable +C<convert_blessed> and provide a C<TO_JSON> method for each object's +(base) class that may be found in the structure, in order to let the +methods replace the objects with whatever scalar values the methods +return. + +If you need to serialise data structures that may contain arbitrary +objects, it's probably better to use other serialisers (such as +L<Sereal> or L<Storable> for example), but if you do want to use +this module for that purpose, C<-convert_blessed_universally> option +may help, which tweaks C<encode> method of the backend to install +C<UNIVERSAL::TO_JSON> method (locally) before encoding, so that +all the objects that don't have their own C<TO_JSON> method can +fall back on the method in the C<UNIVERSAL> namespace. Note that you +still need to enable C<convert_blessed> flag to actually encode +objects in a data structure, and C<UNIVERSAL::TO_JSON> method +installed by this option only converts blessed hash/array references +into their unblessed clone (including private keys/values that are +not supposed to be exposed). Other blessed references will be +converted into null. + +This feature is experimental and may be removed in the future. + +=item -no_export + +When you don't want to import functional interfaces from a module, you +usually supply C<()> to its C<use> statement. + + use JSON (); # no functional interfaces + +If you don't want to import functional interfaces, but you also want to +use any of the above options, add C<-no_export> to the option list. + + # no functional interfaces, while JSON::PP support is enabled. + use JSON -support_by_pp, -no_export; + +=back + +=head1 FUNCTIONAL INTERFACE + +This section is taken from JSON::XS. C<encode_json> and C<decode_json> +are exported by default. + +This module also exports C<to_json> and C<from_json> for backward +compatibility. These are slower, and may expect/generate different stuff +from what C<encode_json> and C<decode_json> do, depending on their +options. It's better just to use Object-Oriented interfaces than using +these two functions. + +=head2 encode_json + + $json_text = encode_json $perl_scalar + +Converts the given Perl data structure to a UTF-8 encoded, binary string +(that is, the string contains octets only). Croaks on error. + +This function call is functionally identical to: + + $json_text = JSON->new->utf8->encode($perl_scalar) + +Except being faster. + +=head2 decode_json + + $perl_scalar = decode_json $json_text + +The opposite of C<encode_json>: expects an UTF-8 (binary) string and tries +to parse that as an UTF-8 encoded JSON text, returning the resulting +reference. Croaks on error. + +This function call is functionally identical to: + + $perl_scalar = JSON->new->utf8->decode($json_text) + +Except being faster. + +=head2 to_json + + $json_text = to_json($perl_scalar[, $optional_hashref]) + +Converts the given Perl data structure to a Unicode string by default. +Croaks on error. + +Basically, this function call is functionally identical to: + + $json_text = JSON->new->encode($perl_scalar) + +Except being slower. + +You can pass an optional hash reference to modify its behavior, but +that may change what C<to_json> expects/generates (see +C<ENCODING/CODESET FLAG NOTES> for details). + + $json_text = to_json($perl_scalar, {utf8 => 1, pretty => 1}) + # => JSON->new->utf8(1)->pretty(1)->encode($perl_scalar) + +=head2 from_json + + $perl_scalar = from_json($json_text[, $optional_hashref]) + +The opposite of C<to_json>: expects a Unicode string and tries +to parse it, returning the resulting reference. Croaks on error. + +Basically, this function call is functionally identical to: + + $perl_scalar = JSON->new->decode($json_text) + +You can pass an optional hash reference to modify its behavior, but +that may change what C<from_json> expects/generates (see +C<ENCODING/CODESET FLAG NOTES> for details). + + $perl_scalar = from_json($json_text, {utf8 => 1}) + # => JSON->new->utf8(1)->decode($json_text) + +=head2 JSON::is_bool + + $is_boolean = JSON::is_bool($scalar) + +Returns true if the passed scalar represents either JSON::true or +JSON::false, two constants that act like C<1> and C<0> respectively +and are also used to represent JSON C<true> and C<false> in Perl strings. + +See L<MAPPING>, below, for more information on how JSON values are mapped to +Perl. + +=head1 COMMON OBJECT-ORIENTED INTERFACE + +This section is also taken from JSON::XS. + +The object oriented interface lets you configure your own encoding or +decoding style, within the limits of supported formats. + +=head2 new + + $json = JSON->new + +Creates a new JSON::XS-compatible backend object that can be used to de/encode JSON +strings. All boolean flags described below are by default I<disabled> +(with the exception of C<allow_nonref>, which defaults to I<enabled> since +version C<4.0>). + +The mutators for flags all return the backend object again and thus calls can +be chained: + + my $json = JSON->new->utf8->space_after->encode({a => [1,2]}) + => {"a": [1, 2]} + +=head2 ascii + + $json = $json->ascii([$enable]) + + $enabled = $json->get_ascii + +If C<$enable> is true (or missing), then the C<encode> method will not +generate characters outside the code range C<0..127> (which is ASCII). Any +Unicode characters outside that range will be escaped using either a +single \uXXXX (BMP characters) or a double \uHHHH\uLLLLL escape sequence, +as per RFC4627. The resulting encoded JSON text can be treated as a native +Unicode string, an ascii-encoded, latin1-encoded or UTF-8 encoded string, +or any other superset of ASCII. + +If C<$enable> is false, then the C<encode> method will not escape Unicode +characters unless required by the JSON syntax or other flags. This results +in a faster and more compact format. + +See also the section I<ENCODING/CODESET FLAG NOTES> later in this document. + +The main use for this flag is to produce JSON texts that can be +transmitted over a 7-bit channel, as the encoded JSON texts will not +contain any 8 bit characters. + + JSON->new->ascii(1)->encode([chr 0x10401]) + => ["\ud801\udc01"] + +=head2 latin1 + + $json = $json->latin1([$enable]) + + $enabled = $json->get_latin1 + +If C<$enable> is true (or missing), then the C<encode> method will encode +the resulting JSON text as latin1 (or iso-8859-1), escaping any characters +outside the code range C<0..255>. The resulting string can be treated as a +latin1-encoded JSON text or a native Unicode string. The C<decode> method +will not be affected in any way by this flag, as C<decode> by default +expects Unicode, which is a strict superset of latin1. + +If C<$enable> is false, then the C<encode> method will not escape Unicode +characters unless required by the JSON syntax or other flags. + +See also the section I<ENCODING/CODESET FLAG NOTES> later in this document. + +The main use for this flag is efficiently encoding binary data as JSON +text, as most octets will not be escaped, resulting in a smaller encoded +size. The disadvantage is that the resulting JSON text is encoded +in latin1 (and must correctly be treated as such when storing and +transferring), a rare encoding for JSON. It is therefore most useful when +you want to store data structures known to contain binary data efficiently +in files or databases, not when talking to other JSON encoders/decoders. + + JSON->new->latin1->encode (["\x{89}\x{abc}"] + => ["\x{89}\\u0abc"] # (perl syntax, U+abc escaped, U+89 not) + +=head2 utf8 + + $json = $json->utf8([$enable]) + + $enabled = $json->get_utf8 + +If C<$enable> is true (or missing), then the C<encode> method will encode +the JSON result into UTF-8, as required by many protocols, while the +C<decode> method expects to be handled an UTF-8-encoded string. Please +note that UTF-8-encoded strings do not contain any characters outside the +range C<0..255>, they are thus useful for bytewise/binary I/O. In future +versions, enabling this option might enable autodetection of the UTF-16 +and UTF-32 encoding families, as described in RFC4627. + +If C<$enable> is false, then the C<encode> method will return the JSON +string as a (non-encoded) Unicode string, while C<decode> expects thus a +Unicode string. Any decoding or encoding (e.g. to UTF-8 or UTF-16) needs +to be done yourself, e.g. using the Encode module. + +See also the section I<ENCODING/CODESET FLAG NOTES> later in this document. + +Example, output UTF-16BE-encoded JSON: + + use Encode; + $jsontext = encode "UTF-16BE", JSON->new->encode ($object); + +Example, decode UTF-32LE-encoded JSON: + + use Encode; + $object = JSON->new->decode (decode "UTF-32LE", $jsontext); + +=head2 pretty + + $json = $json->pretty([$enable]) + +This enables (or disables) all of the C<indent>, C<space_before> and +C<space_after> (and in the future possibly more) flags in one call to +generate the most readable (or most compact) form possible. + +=head2 indent + + $json = $json->indent([$enable]) + + $enabled = $json->get_indent + +If C<$enable> is true (or missing), then the C<encode> method will use a multiline +format as output, putting every array member or object/hash key-value pair +into its own line, indenting them properly. + +If C<$enable> is false, no newlines or indenting will be produced, and the +resulting JSON text is guaranteed not to contain any C<newlines>. + +This setting has no effect when decoding JSON texts. + +=head2 space_before + + $json = $json->space_before([$enable]) + + $enabled = $json->get_space_before + +If C<$enable> is true (or missing), then the C<encode> method will add an extra +optional space before the C<:> separating keys from values in JSON objects. + +If C<$enable> is false, then the C<encode> method will not add any extra +space at those places. + +This setting has no effect when decoding JSON texts. You will also +most likely combine this setting with C<space_after>. + +Example, space_before enabled, space_after and indent disabled: + + {"key" :"value"} + +=head2 space_after + + $json = $json->space_after([$enable]) + + $enabled = $json->get_space_after + +If C<$enable> is true (or missing), then the C<encode> method will add an extra +optional space after the C<:> separating keys from values in JSON objects +and extra whitespace after the C<,> separating key-value pairs and array +members. + +If C<$enable> is false, then the C<encode> method will not add any extra +space at those places. + +This setting has no effect when decoding JSON texts. + +Example, space_before and indent disabled, space_after enabled: + + {"key": "value"} + +=head2 relaxed + + $json = $json->relaxed([$enable]) + + $enabled = $json->get_relaxed + +If C<$enable> is true (or missing), then C<decode> will accept some +extensions to normal JSON syntax (see below). C<encode> will not be +affected in any way. I<Be aware that this option makes you accept invalid +JSON texts as if they were valid!>. I suggest only to use this option to +parse application-specific files written by humans (configuration files, +resource files etc.) + +If C<$enable> is false (the default), then C<decode> will only accept +valid JSON texts. + +Currently accepted extensions are: + +=over 4 + +=item * list items can have an end-comma + +JSON I<separates> array elements and key-value pairs with commas. This +can be annoying if you write JSON texts manually and want to be able to +quickly append elements, so this extension accepts comma at the end of +such items not just between them: + + [ + 1, + 2, <- this comma not normally allowed + ] + { + "k1": "v1", + "k2": "v2", <- this comma not normally allowed + } + +=item * shell-style '#'-comments + +Whenever JSON allows whitespace, shell-style comments are additionally +allowed. They are terminated by the first carriage-return or line-feed +character, after which more white-space and comments are allowed. + + [ + 1, # this comment not allowed in JSON + # neither this one... + ] + +=back + +=head2 canonical + + $json = $json->canonical([$enable]) + + $enabled = $json->get_canonical + +If C<$enable> is true (or missing), then the C<encode> method will output JSON objects +by sorting their keys. This is adding a comparatively high overhead. + +If C<$enable> is false, then the C<encode> method will output key-value +pairs in the order Perl stores them (which will likely change between runs +of the same script, and can change even within the same run from 5.18 +onwards). + +This option is useful if you want the same data structure to be encoded as +the same JSON text (given the same overall settings). If it is disabled, +the same hash might be encoded differently even if contains the same data, +as key-value pairs have no inherent ordering in Perl. + +This setting has no effect when decoding JSON texts. + +This setting has currently no effect on tied hashes. + +=head2 allow_nonref + + $json = $json->allow_nonref([$enable]) + + $enabled = $json->get_allow_nonref + +Unlike other boolean options, this opotion is enabled by default beginning +with version C<4.0>. + +If C<$enable> is true (or missing), then the C<encode> method can convert a +non-reference into its corresponding string, number or null JSON value, +which is an extension to RFC4627. Likewise, C<decode> will accept those JSON +values instead of croaking. + +If C<$enable> is false, then the C<encode> method will croak if it isn't +passed an arrayref or hashref, as JSON texts must either be an object +or array. Likewise, C<decode> will croak if given something that is not a +JSON object or array. + +Example, encode a Perl scalar as JSON value with enabled C<allow_nonref>, +resulting in an invalid JSON text: + + JSON->new->allow_nonref->encode ("Hello, World!") + => "Hello, World!" + +=head2 allow_unknown + + $json = $json->allow_unknown ([$enable]) + + $enabled = $json->get_allow_unknown + +If C<$enable> is true (or missing), then C<encode> will I<not> throw an +exception when it encounters values it cannot represent in JSON (for +example, filehandles) but instead will encode a JSON C<null> value. Note +that blessed objects are not included here and are handled separately by +c<allow_blessed>. + +If C<$enable> is false (the default), then C<encode> will throw an +exception when it encounters anything it cannot encode as JSON. + +This option does not affect C<decode> in any way, and it is recommended to +leave it off unless you know your communications partner. + +=head2 allow_blessed + + $json = $json->allow_blessed([$enable]) + + $enabled = $json->get_allow_blessed + +See L<OBJECT SERIALISATION> for details. + +If C<$enable> is true (or missing), then the C<encode> method will not +barf when it encounters a blessed reference that it cannot convert +otherwise. Instead, a JSON C<null> value is encoded instead of the object. + +If C<$enable> is false (the default), then C<encode> will throw an +exception when it encounters a blessed object that it cannot convert +otherwise. + +This setting has no effect on C<decode>. + +=head2 convert_blessed + + $json = $json->convert_blessed([$enable]) + + $enabled = $json->get_convert_blessed + +See L<OBJECT SERIALISATION> for details. + +If C<$enable> is true (or missing), then C<encode>, upon encountering a +blessed object, will check for the availability of the C<TO_JSON> method +on the object's class. If found, it will be called in scalar context and +the resulting scalar will be encoded instead of the object. + +The C<TO_JSON> method may safely call die if it wants. If C<TO_JSON> +returns other blessed objects, those will be handled in the same +way. C<TO_JSON> must take care of not causing an endless recursion cycle +(== crash) in this case. The name of C<TO_JSON> was chosen because other +methods called by the Perl core (== not by the user of the object) are +usually in upper case letters and to avoid collisions with any C<to_json> +function or method. + +If C<$enable> is false (the default), then C<encode> will not consider +this type of conversion. + +This setting has no effect on C<decode>. + +=head2 allow_tags (since version 3.0) + + $json = $json->allow_tags([$enable]) + + $enabled = $json->get_allow_tags + +See L<OBJECT SERIALISATION> for details. + +If C<$enable> is true (or missing), then C<encode>, upon encountering a +blessed object, will check for the availability of the C<FREEZE> method on +the object's class. If found, it will be used to serialise the object into +a nonstandard tagged JSON value (that JSON decoders cannot decode). + +It also causes C<decode> to parse such tagged JSON values and deserialise +them via a call to the C<THAW> method. + +If C<$enable> is false (the default), then C<encode> will not consider +this type of conversion, and tagged JSON values will cause a parse error +in C<decode>, as if tags were not part of the grammar. + +=head2 boolean_values (since version 4.0) + + $json->boolean_values([$false, $true]) + + ($false, $true) = $json->get_boolean_values + +By default, JSON booleans will be decoded as overloaded +C<$JSON::false> and C<$JSON::true> objects. + +With this method you can specify your own boolean values for decoding - +on decode, JSON C<false> will be decoded as a copy of C<$false>, and JSON +C<true> will be decoded as C<$true> ("copy" here is the same thing as +assigning a value to another variable, i.e. C<$copy = $false>). + +This is useful when you want to pass a decoded data structure directly +to other serialisers like YAML, Data::MessagePack and so on. + +Note that this works only when you C<decode>. You can set incompatible +boolean objects (like L<boolean>), but when you C<encode> a data structure +with such boolean objects, you still need to enable C<convert_blessed> +(and add a C<TO_JSON> method if necessary). + +Calling this method without any arguments will reset the booleans +to their default values. + +C<get_boolean_values> will return both C<$false> and C<$true> values, or +the empty list when they are set to the default. + +=head2 filter_json_object + + $json = $json->filter_json_object([$coderef]) + +When C<$coderef> is specified, it will be called from C<decode> each +time it decodes a JSON object. The only argument is a reference to +the newly-created hash. If the code references returns a single scalar +(which need not be a reference), this value (or rather a copy of it) is +inserted into the deserialised data structure. If it returns an empty +list (NOTE: I<not> C<undef>, which is a valid scalar), the original +deserialised hash will be inserted. This setting can slow down decoding +considerably. + +When C<$coderef> is omitted or undefined, any existing callback will +be removed and C<decode> will not change the deserialised hash in any +way. + +Example, convert all JSON objects into the integer 5: + + my $js = JSON->new->filter_json_object(sub { 5 }); + # returns [5] + $js->decode('[{}]'); + # returns 5 + $js->decode('{"a":1, "b":2}'); + +=head2 filter_json_single_key_object + + $json = $json->filter_json_single_key_object($key [=> $coderef]) + +Works remotely similar to C<filter_json_object>, but is only called for +JSON objects having a single key named C<$key>. + +This C<$coderef> is called before the one specified via +C<filter_json_object>, if any. It gets passed the single value in the JSON +object. If it returns a single value, it will be inserted into the data +structure. If it returns nothing (not even C<undef> but the empty list), +the callback from C<filter_json_object> will be called next, as if no +single-key callback were specified. + +If C<$coderef> is omitted or undefined, the corresponding callback will be +disabled. There can only ever be one callback for a given key. + +As this callback gets called less often then the C<filter_json_object> +one, decoding speed will not usually suffer as much. Therefore, single-key +objects make excellent targets to serialise Perl objects into, especially +as single-key JSON objects are as close to the type-tagged value concept +as JSON gets (it's basically an ID/VALUE tuple). Of course, JSON does not +support this in any way, so you need to make sure your data never looks +like a serialised Perl hash. + +Typical names for the single object key are C<__class_whatever__>, or +C<$__dollars_are_rarely_used__$> or C<}ugly_brace_placement>, or even +things like C<__class_md5sum(classname)__>, to reduce the risk of clashing +with real hashes. + +Example, decode JSON objects of the form C<< { "__widget__" => <id> } >> +into the corresponding C<< $WIDGET{<id>} >> object: + + # return whatever is in $WIDGET{5}: + JSON + ->new + ->filter_json_single_key_object (__widget__ => sub { + $WIDGET{ $_[0] } + }) + ->decode ('{"__widget__": 5') + + # this can be used with a TO_JSON method in some "widget" class + # for serialisation to json: + sub WidgetBase::TO_JSON { + my ($self) = @_; + + unless ($self->{id}) { + $self->{id} = ..get..some..id..; + $WIDGET{$self->{id}} = $self; + } + + { __widget__ => $self->{id} } + } + +=head2 max_depth + + $json = $json->max_depth([$maximum_nesting_depth]) + + $max_depth = $json->get_max_depth + +Sets the maximum nesting level (default C<512>) accepted while encoding +or decoding. If a higher nesting level is detected in JSON text or a Perl +data structure, then the encoder and decoder will stop and croak at that +point. + +Nesting level is defined by number of hash- or arrayrefs that the encoder +needs to traverse to reach a given point or the number of C<{> or C<[> +characters without their matching closing parenthesis crossed to reach a +given character in a string. + +Setting the maximum depth to one disallows any nesting, so that ensures +that the object is only a single hash/object or array. + +If no argument is given, the highest possible setting will be used, which +is rarely useful. + +See L<JSON::XS/SECURITY CONSIDERATIONS> for more info on why this is useful. + +=head2 max_size + + $json = $json->max_size([$maximum_string_size]) + + $max_size = $json->get_max_size + +Set the maximum length a JSON text may have (in bytes) where decoding is +being attempted. The default is C<0>, meaning no limit. When C<decode> +is called on a string that is longer then this many bytes, it will not +attempt to decode the string but throw an exception. This setting has no +effect on C<encode> (yet). + +If no argument is given, the limit check will be deactivated (same as when +C<0> is specified). + +See L<JSON::XS/SECURITY CONSIDERATIONS> for more info on why this is useful. + +=head2 encode + + $json_text = $json->encode($perl_scalar) + +Converts the given Perl value or data structure to its JSON +representation. Croaks on error. + +=head2 decode + + $perl_scalar = $json->decode($json_text) + +The opposite of C<encode>: expects a JSON text and tries to parse it, +returning the resulting simple scalar or reference. Croaks on error. + +=head2 decode_prefix + + ($perl_scalar, $characters) = $json->decode_prefix($json_text) + +This works like the C<decode> method, but instead of raising an exception +when there is trailing garbage after the first JSON object, it will +silently stop parsing there and return the number of characters consumed +so far. + +This is useful if your JSON texts are not delimited by an outer protocol +and you need to know where the JSON text ends. + + JSON->new->decode_prefix ("[1] the tail") + => ([1], 3) + +=head1 ADDITIONAL METHODS + +The following methods are for this module only. + +=head2 backend + + $backend = $json->backend + +Since 2.92, C<backend> method returns an abstract backend module used currently, +which should be JSON::Backend::XS (which inherits JSON::XS or Cpanel::JSON::XS), +or JSON::Backend::PP (which inherits JSON::PP), not to monkey-patch the actual +backend module globally. + +If you need to know what is used actually, use C<isa>, instead of string comparison. + +=head2 is_xs + + $boolean = $json->is_xs + +Returns true if the backend inherits JSON::XS or Cpanel::JSON::XS. + +=head2 is_pp + + $boolean = $json->is_pp + +Returns true if the backend inherits JSON::PP. + +=head2 property + + $settings = $json->property() + +Returns a reference to a hash that holds all the common flag settings. + + $json = $json->property('utf8' => 1) + $value = $json->property('utf8') # 1 + +You can use this to get/set a value of a particular flag. + +=head2 boolean + + $boolean_object = JSON->boolean($scalar) + +Returns $JSON::true if $scalar contains a true value, $JSON::false otherwise. +You can use this as a full-qualified function (C<JSON::boolean($scalar)>). + +=head1 INCREMENTAL PARSING + +This section is also taken from JSON::XS. + +In some cases, there is the need for incremental parsing of JSON +texts. While this module always has to keep both JSON text and resulting +Perl data structure in memory at one time, it does allow you to parse a +JSON stream incrementally. It does so by accumulating text until it has +a full JSON object, which it then can decode. This process is similar to +using C<decode_prefix> to see if a full JSON object is available, but +is much more efficient (and can be implemented with a minimum of method +calls). + +This module will only attempt to parse the JSON text once it is sure it +has enough text to get a decisive result, using a very simple but +truly incremental parser. This means that it sometimes won't stop as +early as the full parser, for example, it doesn't detect mismatched +parentheses. The only thing it guarantees is that it starts decoding as +soon as a syntactically valid JSON text has been seen. This means you need +to set resource limits (e.g. C<max_size>) to ensure the parser will stop +parsing in the presence if syntax errors. + +The following methods implement this incremental parser. + +=head2 incr_parse + + $json->incr_parse( [$string] ) # void context + + $obj_or_undef = $json->incr_parse( [$string] ) # scalar context + + @obj_or_empty = $json->incr_parse( [$string] ) # list context + +This is the central parsing function. It can both append new text and +extract objects from the stream accumulated so far (both of these +functions are optional). + +If C<$string> is given, then this string is appended to the already +existing JSON fragment stored in the C<$json> object. + +After that, if the function is called in void context, it will simply +return without doing anything further. This can be used to add more text +in as many chunks as you want. + +If the method is called in scalar context, then it will try to extract +exactly I<one> JSON object. If that is successful, it will return this +object, otherwise it will return C<undef>. If there is a parse error, +this method will croak just as C<decode> would do (one can then use +C<incr_skip> to skip the erroneous part). This is the most common way of +using the method. + +And finally, in list context, it will try to extract as many objects +from the stream as it can find and return them, or the empty list +otherwise. For this to work, there must be no separators (other than +whitespace) between the JSON objects or arrays, instead they must be +concatenated back-to-back. If an error occurs, an exception will be +raised as in the scalar context case. Note that in this case, any +previously-parsed JSON texts will be lost. + +Example: Parse some JSON arrays/objects in a given string and return +them. + + my @objs = JSON->new->incr_parse ("[5][7][1,2]"); + +=head2 incr_text + + $lvalue_string = $json->incr_text + +This method returns the currently stored JSON fragment as an lvalue, that +is, you can manipulate it. This I<only> works when a preceding call to +C<incr_parse> in I<scalar context> successfully returned an object. Under +all other circumstances you must not call this function (I mean it. +although in simple tests it might actually work, it I<will> fail under +real world conditions). As a special exception, you can also call this +method before having parsed anything. + +That means you can only use this function to look at or manipulate text +before or after complete JSON objects, not while the parser is in the +middle of parsing a JSON object. + +This function is useful in two cases: a) finding the trailing text after a +JSON object or b) parsing multiple JSON objects separated by non-JSON text +(such as commas). + +=head2 incr_skip + + $json->incr_skip + +This will reset the state of the incremental parser and will remove +the parsed text from the input buffer so far. This is useful after +C<incr_parse> died, in which case the input buffer and incremental parser +state is left unchanged, to skip the text parsed so far and to reset the +parse state. + +The difference to C<incr_reset> is that only text until the parse error +occurred is removed. + +=head2 incr_reset + + $json->incr_reset + +This completely resets the incremental parser, that is, after this call, +it will be as if the parser had never parsed anything. + +This is useful if you want to repeatedly parse JSON objects and want to +ignore any trailing data, which means you have to reset the parser after +each successful decode. + +=head1 MAPPING + +Most of this section is also taken from JSON::XS. + +This section describes how the backend modules map Perl values to JSON values and +vice versa. These mappings are designed to "do the right thing" in most +circumstances automatically, preserving round-tripping characteristics +(what you put in comes out as something equivalent). + +For the more enlightened: note that in the following descriptions, +lowercase I<perl> refers to the Perl interpreter, while uppercase I<Perl> +refers to the abstract Perl language itself. + +=head2 JSON -> PERL + +=over 4 + +=item object + +A JSON object becomes a reference to a hash in Perl. No ordering of object +keys is preserved (JSON does not preserver object key ordering itself). + +=item array + +A JSON array becomes a reference to an array in Perl. + +=item string + +A JSON string becomes a string scalar in Perl - Unicode codepoints in JSON +are represented by the same codepoints in the Perl string, so no manual +decoding is necessary. + +=item number + +A JSON number becomes either an integer, numeric (floating point) or +string scalar in perl, depending on its range and any fractional parts. On +the Perl level, there is no difference between those as Perl handles all +the conversion details, but an integer may take slightly less memory and +might represent more values exactly than floating point numbers. + +If the number consists of digits only, this module will try to represent +it as an integer value. If that fails, it will try to represent it as +a numeric (floating point) value if that is possible without loss of +precision. Otherwise it will preserve the number as a string value (in +which case you lose roundtripping ability, as the JSON number will be +re-encoded to a JSON string). + +Numbers containing a fractional or exponential part will always be +represented as numeric (floating point) values, possibly at a loss of +precision (in which case you might lose perfect roundtripping ability, but +the JSON number will still be re-encoded as a JSON number). + +Note that precision is not accuracy - binary floating point values cannot +represent most decimal fractions exactly, and when converting from and to +floating point, this module only guarantees precision up to but not including +the least significant bit. + +=item true, false + +These JSON atoms become C<JSON::true> and C<JSON::false>, +respectively. They are overloaded to act almost exactly like the numbers +C<1> and C<0>. You can check whether a scalar is a JSON boolean by using +the C<JSON::is_bool> function. + +=item null + +A JSON null atom becomes C<undef> in Perl. + +=item shell-style comments (C<< # I<text> >>) + +As a nonstandard extension to the JSON syntax that is enabled by the +C<relaxed> setting, shell-style comments are allowed. They can start +anywhere outside strings and go till the end of the line. + +=item tagged values (C<< (I<tag>)I<value> >>). + +Another nonstandard extension to the JSON syntax, enabled with the +C<allow_tags> setting, are tagged values. In this implementation, the +I<tag> must be a perl package/class name encoded as a JSON string, and the +I<value> must be a JSON array encoding optional constructor arguments. + +See L<OBJECT SERIALISATION>, below, for details. + +=back + + +=head2 PERL -> JSON + +The mapping from Perl to JSON is slightly more difficult, as Perl is a +truly typeless language, so we can only guess which JSON type is meant by +a Perl value. + +=over 4 + +=item hash references + +Perl hash references become JSON objects. As there is no inherent +ordering in hash keys (or JSON objects), they will usually be encoded +in a pseudo-random order. This module can optionally sort the hash keys +(determined by the I<canonical> flag), so the same data structure will +serialise to the same JSON text (given same settings and version of +the same backend), but this incurs a runtime overhead and is only rarely useful, +e.g. when you want to compare some JSON text against another for equality. + +=item array references + +Perl array references become JSON arrays. + +=item other references + +Other unblessed references are generally not allowed and will cause an +exception to be thrown, except for references to the integers C<0> and +C<1>, which get turned into C<false> and C<true> atoms in JSON. You can +also use C<JSON::false> and C<JSON::true> to improve readability. + + encode_json [\0,JSON::true] # yields [false,true] + +=item JSON::true, JSON::false, JSON::null + +These special values become JSON true and JSON false values, +respectively. You can also use C<\1> and C<\0> directly if you want. + +=item blessed objects + +Blessed objects are not directly representable in JSON, but C<JSON::XS> +allows various ways of handling objects. See L<OBJECT SERIALISATION>, +below, for details. + +=item simple scalars + +Simple Perl scalars (any scalar that is not a reference) are the most +difficult objects to encode: this module will encode undefined scalars as +JSON C<null> values, scalars that have last been used in a string context +before encoding as JSON strings, and anything else as number value: + + # dump as number + encode_json [2] # yields [2] + encode_json [-3.0e17] # yields [-3e+17] + my $value = 5; encode_json [$value] # yields [5] + + # used as string, so dump as string + print $value; + encode_json [$value] # yields ["5"] + + # undef becomes null + encode_json [undef] # yields [null] + +You can force the type to be a string by stringifying it: + + my $x = 3.1; # some variable containing a number + "$x"; # stringified + $x .= ""; # another, more awkward way to stringify + print $x; # perl does it for you, too, quite often + +You can force the type to be a number by numifying it: + + my $x = "3"; # some variable containing a string + $x += 0; # numify it, ensuring it will be dumped as a number + $x *= 1; # same thing, the choice is yours. + +You can not currently force the type in other, less obscure, ways. Tell me +if you need this capability (but don't forget to explain why it's needed +:). + +Since version 2.91_01, JSON::PP uses a different number detection logic +that converts a scalar that is possible to turn into a number safely. +The new logic is slightly faster, and tends to help people who use older +perl or who want to encode complicated data structure. However, this may +results in a different JSON text from the one JSON::XS encodes (and +thus may break tests that compare entire JSON texts). If you do +need the previous behavior for better compatibility or for finer control, +set PERL_JSON_PP_USE_B environmental variable to true before you +C<use> JSON. + +Note that numerical precision has the same meaning as under Perl (so +binary to decimal conversion follows the same rules as in Perl, which +can differ to other languages). Also, your perl interpreter might expose +extensions to the floating point numbers of your platform, such as +infinities or NaN's - these cannot be represented in JSON, and it is an +error to pass those in. + +JSON.pm backend modules trust what you pass to C<encode> method +(or C<encode_json> function) is a clean, validated data structure with +values that can be represented as valid JSON values only, because it's +not from an external data source (as opposed to JSON texts you pass to +C<decode> or C<decode_json>, which JSON backends consider tainted and +don't trust). As JSON backends don't know exactly what you and consumers +of your JSON texts want the unexpected values to be (you may want to +convert them into null, or to stringify them with or without +normalisation (string representation of infinities/NaN may vary +depending on platforms), or to croak without conversion), you're advised +to do what you and your consumers need before you encode, and also not +to numify values that may start with values that look like a number +(including infinities/NaN), without validating. + +=back + +=head2 OBJECT SERIALISATION + +As JSON cannot directly represent Perl objects, you have to choose between +a pure JSON representation (without the ability to deserialise the object +automatically again), and a nonstandard extension to the JSON syntax, +tagged values. + +=head3 SERIALISATION + +What happens when this module encounters a Perl object depends on the +C<allow_blessed>, C<convert_blessed> and C<allow_tags> settings, which +are used in this order: + +=over 4 + +=item 1. C<allow_tags> is enabled and the object has a C<FREEZE> method. + +In this case, C<JSON> creates a tagged JSON value, using a nonstandard +extension to the JSON syntax. + +This works by invoking the C<FREEZE> method on the object, with the first +argument being the object to serialise, and the second argument being the +constant string C<JSON> to distinguish it from other serialisers. + +The C<FREEZE> method can return any number of values (i.e. zero or +more). These values and the paclkage/classname of the object will then be +encoded as a tagged JSON value in the following format: + + ("classname")[FREEZE return values...] + +e.g.: + + ("URI")["http://www.google.com/"] + ("MyDate")[2013,10,29] + ("ImageData::JPEG")["Z3...VlCg=="] + +For example, the hypothetical C<My::Object> C<FREEZE> method might use the +objects C<type> and C<id> members to encode the object: + + sub My::Object::FREEZE { + my ($self, $serialiser) = @_; + + ($self->{type}, $self->{id}) + } + +=item 2. C<convert_blessed> is enabled and the object has a C<TO_JSON> method. + +In this case, the C<TO_JSON> method of the object is invoked in scalar +context. It must return a single scalar that can be directly encoded into +JSON. This scalar replaces the object in the JSON text. + +For example, the following C<TO_JSON> method will convert all L<URI> +objects to JSON strings when serialised. The fact that these values +originally were L<URI> objects is lost. + + sub URI::TO_JSON { + my ($uri) = @_; + $uri->as_string + } + +=item 3. C<allow_blessed> is enabled. + +The object will be serialised as a JSON null value. + +=item 4. none of the above + +If none of the settings are enabled or the respective methods are missing, +this module throws an exception. + +=back + +=head3 DESERIALISATION + +For deserialisation there are only two cases to consider: either +nonstandard tagging was used, in which case C<allow_tags> decides, +or objects cannot be automatically be deserialised, in which +case you can use postprocessing or the C<filter_json_object> or +C<filter_json_single_key_object> callbacks to get some real objects our of +your JSON. + +This section only considers the tagged value case: a tagged JSON object +is encountered during decoding and C<allow_tags> is disabled, a parse +error will result (as if tagged values were not part of the grammar). + +If C<allow_tags> is enabled, this module will look up the C<THAW> method +of the package/classname used during serialisation (it will not attempt +to load the package as a Perl module). If there is no such method, the +decoding will fail with an error. + +Otherwise, the C<THAW> method is invoked with the classname as first +argument, the constant string C<JSON> as second argument, and all the +values from the JSON array (the values originally returned by the +C<FREEZE> method) as remaining arguments. + +The method must then return the object. While technically you can return +any Perl scalar, you might have to enable the C<allow_nonref> setting to +make that work in all cases, so better return an actual blessed reference. + +As an example, let's implement a C<THAW> function that regenerates the +C<My::Object> from the C<FREEZE> example earlier: + + sub My::Object::THAW { + my ($class, $serialiser, $type, $id) = @_; + + $class->new (type => $type, id => $id) + } + + +=head1 ENCODING/CODESET FLAG NOTES + +This section is taken from JSON::XS. + +The interested reader might have seen a number of flags that signify +encodings or codesets - C<utf8>, C<latin1> and C<ascii>. There seems to be +some confusion on what these do, so here is a short comparison: + +C<utf8> controls whether the JSON text created by C<encode> (and expected +by C<decode>) is UTF-8 encoded or not, while C<latin1> and C<ascii> only +control whether C<encode> escapes character values outside their respective +codeset range. Neither of these flags conflict with each other, although +some combinations make less sense than others. + +Care has been taken to make all flags symmetrical with respect to +C<encode> and C<decode>, that is, texts encoded with any combination of +these flag values will be correctly decoded when the same flags are used +- in general, if you use different flag settings while encoding vs. when +decoding you likely have a bug somewhere. + +Below comes a verbose discussion of these flags. Note that a "codeset" is +simply an abstract set of character-codepoint pairs, while an encoding +takes those codepoint numbers and I<encodes> them, in our case into +octets. Unicode is (among other things) a codeset, UTF-8 is an encoding, +and ISO-8859-1 (= latin 1) and ASCII are both codesets I<and> encodings at +the same time, which can be confusing. + +=over 4 + +=item C<utf8> flag disabled + +When C<utf8> is disabled (the default), then C<encode>/C<decode> generate +and expect Unicode strings, that is, characters with high ordinal Unicode +values (> 255) will be encoded as such characters, and likewise such +characters are decoded as-is, no changes to them will be done, except +"(re-)interpreting" them as Unicode codepoints or Unicode characters, +respectively (to Perl, these are the same thing in strings unless you do +funny/weird/dumb stuff). + +This is useful when you want to do the encoding yourself (e.g. when you +want to have UTF-16 encoded JSON texts) or when some other layer does +the encoding for you (for example, when printing to a terminal using a +filehandle that transparently encodes to UTF-8 you certainly do NOT want +to UTF-8 encode your data first and have Perl encode it another time). + +=item C<utf8> flag enabled + +If the C<utf8>-flag is enabled, C<encode>/C<decode> will encode all +characters using the corresponding UTF-8 multi-byte sequence, and will +expect your input strings to be encoded as UTF-8, that is, no "character" +of the input string must have any value > 255, as UTF-8 does not allow +that. + +The C<utf8> flag therefore switches between two modes: disabled means you +will get a Unicode string in Perl, enabled means you get an UTF-8 encoded +octet/binary string in Perl. + +=item C<latin1> or C<ascii> flags enabled + +With C<latin1> (or C<ascii>) enabled, C<encode> will escape characters +with ordinal values > 255 (> 127 with C<ascii>) and encode the remaining +characters as specified by the C<utf8> flag. + +If C<utf8> is disabled, then the result is also correctly encoded in those +character sets (as both are proper subsets of Unicode, meaning that a +Unicode string with all character values < 256 is the same thing as a +ISO-8859-1 string, and a Unicode string with all character values < 128 is +the same thing as an ASCII string in Perl). + +If C<utf8> is enabled, you still get a correct UTF-8-encoded string, +regardless of these flags, just some more characters will be escaped using +C<\uXXXX> then before. + +Note that ISO-8859-1-I<encoded> strings are not compatible with UTF-8 +encoding, while ASCII-encoded strings are. That is because the ISO-8859-1 +encoding is NOT a subset of UTF-8 (despite the ISO-8859-1 I<codeset> being +a subset of Unicode), while ASCII is. + +Surprisingly, C<decode> will ignore these flags and so treat all input +values as governed by the C<utf8> flag. If it is disabled, this allows you +to decode ISO-8859-1- and ASCII-encoded strings, as both strict subsets of +Unicode. If it is enabled, you can correctly decode UTF-8 encoded strings. + +So neither C<latin1> nor C<ascii> are incompatible with the C<utf8> flag - +they only govern when the JSON output engine escapes a character or not. + +The main use for C<latin1> is to relatively efficiently store binary data +as JSON, at the expense of breaking compatibility with most JSON decoders. + +The main use for C<ascii> is to force the output to not contain characters +with values > 127, which means you can interpret the resulting string +as UTF-8, ISO-8859-1, ASCII, KOI8-R or most about any character set and +8-bit-encoding, and still get the same data structure back. This is useful +when your channel for JSON transfer is not 8-bit clean or the encoding +might be mangled in between (e.g. in mail), and works because ASCII is a +proper subset of most 8-bit and multibyte encodings in use in the world. + +=back + +=head1 BACKWARD INCOMPATIBILITY + +Since version 2.90, stringification (and string comparison) for +C<JSON::true> and C<JSON::false> has not been overloaded. It shouldn't +matter as long as you treat them as boolean values, but a code that +expects they are stringified as "true" or "false" doesn't work as +you have expected any more. + + if (JSON::true eq 'true') { # now fails + + print "The result is $JSON::true now."; # => The result is 1 now. + +And now these boolean values don't inherit JSON::Boolean, either. +When you need to test a value is a JSON boolean value or not, use +C<JSON::is_bool> function, instead of testing the value inherits +a particular boolean class or not. + +=head1 BUGS + +Please report bugs on backend selection and additional features +this module provides to RT or GitHub issues for this module: + +L<https://rt.cpan.org/Public/Dist/Display.html?Queue=JSON> + +L<https://github.com/makamaka/JSON/issues> + +As for bugs on a specific behavior, please report to the author +of the backend module you are using. + +As for new features and requests to change common behaviors, please +ask the author of JSON::XS (Marc Lehmann, E<lt>schmorp[at]schmorp.deE<gt>) +first, by email (important!), to keep compatibility among JSON.pm +backends. + +=head1 SEE ALSO + +L<JSON::XS>, L<Cpanel::JSON::XS>, L<JSON::PP> for backends. + +L<JSON::MaybeXS>, an alternative that prefers Cpanel::JSON::XS. + +C<RFC4627>(L<http://www.ietf.org/rfc/rfc4627.txt>) + +RFC7159 (L<http://www.ietf.org/rfc/rfc7159.txt>) + +RFC8259 (L<http://www.ietf.org/rfc/rfc8259.txt>) + +=head1 AUTHOR + +Makamaka Hannyaharamitu, E<lt>makamaka[at]cpan.orgE<gt> + +JSON::XS was written by Marc Lehmann E<lt>schmorp[at]schmorp.deE<gt> + +The release of this new version owes to the courtesy of Marc Lehmann. + +=head1 CURRENT MAINTAINER + +Kenichi Ishigaki, E<lt>ishigaki[at]cpan.orgE<gt> + +=head1 COPYRIGHT AND LICENSE + +Copyright 2005-2013 by Makamaka Hannyaharamitu + +Most of the documentation is taken from JSON::XS by Marc Lehmann + +This library is free software; you can redistribute it and/or modify +it under the same terms as Perl itself. + +=cut + diff --git a/lib/JSON/backportPP.pm b/lib/JSON/backportPP.pm new file mode 100644 index 0000000..6f9b949 --- /dev/null +++ b/lib/JSON/backportPP.pm @@ -0,0 +1,3150 @@ +package # This is JSON::backportPP + JSON::PP; + +# JSON-2.0 + +use 5.005; +use strict; + +use Exporter (); +BEGIN { @JSON::backportPP::ISA = ('Exporter') } + +use overload (); +use JSON::backportPP::Boolean; + +use Carp (); +#use Devel::Peek; + +$JSON::backportPP::VERSION = '4.02'; + +@JSON::PP::EXPORT = qw(encode_json decode_json from_json to_json); + +# instead of hash-access, i tried index-access for speed. +# but this method is not faster than what i expected. so it will be changed. + +use constant P_ASCII => 0; +use constant P_LATIN1 => 1; +use constant P_UTF8 => 2; +use constant P_INDENT => 3; +use constant P_CANONICAL => 4; +use constant P_SPACE_BEFORE => 5; +use constant P_SPACE_AFTER => 6; +use constant P_ALLOW_NONREF => 7; +use constant P_SHRINK => 8; +use constant P_ALLOW_BLESSED => 9; +use constant P_CONVERT_BLESSED => 10; +use constant P_RELAXED => 11; + +use constant P_LOOSE => 12; +use constant P_ALLOW_BIGNUM => 13; +use constant P_ALLOW_BAREKEY => 14; +use constant P_ALLOW_SINGLEQUOTE => 15; +use constant P_ESCAPE_SLASH => 16; +use constant P_AS_NONBLESSED => 17; + +use constant P_ALLOW_UNKNOWN => 18; +use constant P_ALLOW_TAGS => 19; + +use constant OLD_PERL => $] < 5.008 ? 1 : 0; +use constant USE_B => $ENV{PERL_JSON_PP_USE_B} || 0; + +BEGIN { + if (USE_B) { + require B; + } +} + +BEGIN { + my @xs_compati_bit_properties = qw( + latin1 ascii utf8 indent canonical space_before space_after allow_nonref shrink + allow_blessed convert_blessed relaxed allow_unknown + allow_tags + ); + my @pp_bit_properties = qw( + allow_singlequote allow_bignum loose + allow_barekey escape_slash as_nonblessed + ); + + # Perl version check, Unicode handling is enabled? + # Helper module sets @JSON::PP::_properties. + if ( OLD_PERL ) { + my $helper = $] >= 5.006 ? 'JSON::backportPP::Compat5006' : 'JSON::backportPP::Compat5005'; + eval qq| require $helper |; + if ($@) { Carp::croak $@; } + } + + for my $name (@xs_compati_bit_properties, @pp_bit_properties) { + my $property_id = 'P_' . uc($name); + + eval qq/ + sub $name { + my \$enable = defined \$_[1] ? \$_[1] : 1; + + if (\$enable) { + \$_[0]->{PROPS}->[$property_id] = 1; + } + else { + \$_[0]->{PROPS}->[$property_id] = 0; + } + + \$_[0]; + } + + sub get_$name { + \$_[0]->{PROPS}->[$property_id] ? 1 : ''; + } + /; + } + +} + + + +# Functions + +my $JSON; # cache + +sub encode_json ($) { # encode + ($JSON ||= __PACKAGE__->new->utf8)->encode(@_); +} + + +sub decode_json { # decode + ($JSON ||= __PACKAGE__->new->utf8)->decode(@_); +} + +# Obsoleted + +sub to_json($) { + Carp::croak ("JSON::PP::to_json has been renamed to encode_json."); +} + + +sub from_json($) { + Carp::croak ("JSON::PP::from_json has been renamed to decode_json."); +} + + +# Methods + +sub new { + my $class = shift; + my $self = { + max_depth => 512, + max_size => 0, + indent_length => 3, + }; + + $self->{PROPS}[P_ALLOW_NONREF] = 1; + + bless $self, $class; +} + + +sub encode { + return $_[0]->PP_encode_json($_[1]); +} + + +sub decode { + return $_[0]->PP_decode_json($_[1], 0x00000000); +} + + +sub decode_prefix { + return $_[0]->PP_decode_json($_[1], 0x00000001); +} + + +# accessor + + +# pretty printing + +sub pretty { + my ($self, $v) = @_; + my $enable = defined $v ? $v : 1; + + if ($enable) { # indent_length(3) for JSON::XS compatibility + $self->indent(1)->space_before(1)->space_after(1); + } + else { + $self->indent(0)->space_before(0)->space_after(0); + } + + $self; +} + +# etc + +sub max_depth { + my $max = defined $_[1] ? $_[1] : 0x80000000; + $_[0]->{max_depth} = $max; + $_[0]; +} + + +sub get_max_depth { $_[0]->{max_depth}; } + + +sub max_size { + my $max = defined $_[1] ? $_[1] : 0; + $_[0]->{max_size} = $max; + $_[0]; +} + + +sub get_max_size { $_[0]->{max_size}; } + +sub boolean_values { + my $self = shift; + if (@_) { + my ($false, $true) = @_; + $self->{false} = $false; + $self->{true} = $true; + return ($false, $true); + } else { + delete $self->{false}; + delete $self->{true}; + return; + } +} + +sub get_boolean_values { + my $self = shift; + if (exists $self->{true} and exists $self->{false}) { + return @$self{qw/false true/}; + } + return; +} + +sub filter_json_object { + if (defined $_[1] and ref $_[1] eq 'CODE') { + $_[0]->{cb_object} = $_[1]; + } else { + delete $_[0]->{cb_object}; + } + $_[0]->{F_HOOK} = ($_[0]->{cb_object} or $_[0]->{cb_sk_object}) ? 1 : 0; + $_[0]; +} + +sub filter_json_single_key_object { + if (@_ == 1 or @_ > 3) { + Carp::croak("Usage: JSON::PP::filter_json_single_key_object(self, key, callback = undef)"); + } + if (defined $_[2] and ref $_[2] eq 'CODE') { + $_[0]->{cb_sk_object}->{$_[1]} = $_[2]; + } else { + delete $_[0]->{cb_sk_object}->{$_[1]}; + delete $_[0]->{cb_sk_object} unless %{$_[0]->{cb_sk_object} || {}}; + } + $_[0]->{F_HOOK} = ($_[0]->{cb_object} or $_[0]->{cb_sk_object}) ? 1 : 0; + $_[0]; +} + +sub indent_length { + if (!defined $_[1] or $_[1] > 15 or $_[1] < 0) { + Carp::carp "The acceptable range of indent_length() is 0 to 15."; + } + else { + $_[0]->{indent_length} = $_[1]; + } + $_[0]; +} + +sub get_indent_length { + $_[0]->{indent_length}; +} + +sub sort_by { + $_[0]->{sort_by} = defined $_[1] ? $_[1] : 1; + $_[0]; +} + +sub allow_bigint { + Carp::carp("allow_bigint() is obsoleted. use allow_bignum() instead."); + $_[0]->allow_bignum; +} + +############################### + +### +### Perl => JSON +### + + +{ # Convert + + my $max_depth; + my $indent; + my $ascii; + my $latin1; + my $utf8; + my $space_before; + my $space_after; + my $canonical; + my $allow_blessed; + my $convert_blessed; + + my $indent_length; + my $escape_slash; + my $bignum; + my $as_nonblessed; + my $allow_tags; + + my $depth; + my $indent_count; + my $keysort; + + + sub PP_encode_json { + my $self = shift; + my $obj = shift; + + $indent_count = 0; + $depth = 0; + + my $props = $self->{PROPS}; + + ($ascii, $latin1, $utf8, $indent, $canonical, $space_before, $space_after, $allow_blessed, + $convert_blessed, $escape_slash, $bignum, $as_nonblessed, $allow_tags) + = @{$props}[P_ASCII .. P_SPACE_AFTER, P_ALLOW_BLESSED, P_CONVERT_BLESSED, + P_ESCAPE_SLASH, P_ALLOW_BIGNUM, P_AS_NONBLESSED, P_ALLOW_TAGS]; + + ($max_depth, $indent_length) = @{$self}{qw/max_depth indent_length/}; + + $keysort = $canonical ? sub { $a cmp $b } : undef; + + if ($self->{sort_by}) { + $keysort = ref($self->{sort_by}) eq 'CODE' ? $self->{sort_by} + : $self->{sort_by} =~ /\D+/ ? $self->{sort_by} + : sub { $a cmp $b }; + } + + encode_error("hash- or arrayref expected (not a simple scalar, use allow_nonref to allow this)") + if(!ref $obj and !$props->[ P_ALLOW_NONREF ]); + + my $str = $self->object_to_json($obj); + + $str .= "\n" if ( $indent ); # JSON::XS 2.26 compatible + + unless ($ascii or $latin1 or $utf8) { + utf8::upgrade($str); + } + + if ($props->[ P_SHRINK ]) { + utf8::downgrade($str, 1); + } + + return $str; + } + + + sub object_to_json { + my ($self, $obj) = @_; + my $type = ref($obj); + + if($type eq 'HASH'){ + return $self->hash_to_json($obj); + } + elsif($type eq 'ARRAY'){ + return $self->array_to_json($obj); + } + elsif ($type) { # blessed object? + if (blessed($obj)) { + + return $self->value_to_json($obj) if ( $obj->isa('JSON::PP::Boolean') ); + + if ( $allow_tags and $obj->can('FREEZE') ) { + my $obj_class = ref $obj || $obj; + $obj = bless $obj, $obj_class; + my @results = $obj->FREEZE('JSON'); + if ( @results and ref $results[0] ) { + if ( refaddr( $obj ) eq refaddr( $results[0] ) ) { + encode_error( sprintf( + "%s::FREEZE method returned same object as was passed instead of a new one", + ref $obj + ) ); + } + } + return '("'.$obj_class.'")['.join(',', @results).']'; + } + + if ( $convert_blessed and $obj->can('TO_JSON') ) { + my $result = $obj->TO_JSON(); + if ( defined $result and ref( $result ) ) { + if ( refaddr( $obj ) eq refaddr( $result ) ) { + encode_error( sprintf( + "%s::TO_JSON method returned same object as was passed instead of a new one", + ref $obj + ) ); + } + } + + return $self->object_to_json( $result ); + } + + return "$obj" if ( $bignum and _is_bignum($obj) ); + + if ($allow_blessed) { + return $self->blessed_to_json($obj) if ($as_nonblessed); # will be removed. + return 'null'; + } + encode_error( sprintf("encountered object '%s', but neither allow_blessed, convert_blessed nor allow_tags settings are enabled (or TO_JSON/FREEZE method missing)", $obj) + ); + } + else { + return $self->value_to_json($obj); + } + } + else{ + return $self->value_to_json($obj); + } + } + + + sub hash_to_json { + my ($self, $obj) = @_; + my @res; + + encode_error("json text or perl structure exceeds maximum nesting level (max_depth set too low?)") + if (++$depth > $max_depth); + + my ($pre, $post) = $indent ? $self->_up_indent() : ('', ''); + my $del = ($space_before ? ' ' : '') . ':' . ($space_after ? ' ' : ''); + + for my $k ( _sort( $obj ) ) { + if ( OLD_PERL ) { utf8::decode($k) } # key for Perl 5.6 / be optimized + push @res, $self->string_to_json( $k ) + . $del + . ( ref $obj->{$k} ? $self->object_to_json( $obj->{$k} ) : $self->value_to_json( $obj->{$k} ) ); + } + + --$depth; + $self->_down_indent() if ($indent); + + return '{}' unless @res; + return '{' . $pre . join( ",$pre", @res ) . $post . '}'; + } + + + sub array_to_json { + my ($self, $obj) = @_; + my @res; + + encode_error("json text or perl structure exceeds maximum nesting level (max_depth set too low?)") + if (++$depth > $max_depth); + + my ($pre, $post) = $indent ? $self->_up_indent() : ('', ''); + + for my $v (@$obj){ + push @res, ref($v) ? $self->object_to_json($v) : $self->value_to_json($v); + } + + --$depth; + $self->_down_indent() if ($indent); + + return '[]' unless @res; + return '[' . $pre . join( ",$pre", @res ) . $post . ']'; + } + + sub _looks_like_number { + my $value = shift; + if (USE_B) { + my $b_obj = B::svref_2object(\$value); + my $flags = $b_obj->FLAGS; + return 1 if $flags & ( B::SVp_IOK() | B::SVp_NOK() ) and !( $flags & B::SVp_POK() ); + return; + } else { + no warnings 'numeric'; + # if the utf8 flag is on, it almost certainly started as a string + return if utf8::is_utf8($value); + # detect numbers + # string & "" -> "" + # number & "" -> 0 (with warning) + # nan and inf can detect as numbers, so check with * 0 + return unless length((my $dummy = "") & $value); + return unless 0 + $value eq $value; + return 1 if $value * 0 == 0; + return -1; # inf/nan + } + } + + sub value_to_json { + my ($self, $value) = @_; + + return 'null' if(!defined $value); + + my $type = ref($value); + + if (!$type) { + if (_looks_like_number($value)) { + return $value; + } + return $self->string_to_json($value); + } + elsif( blessed($value) and $value->isa('JSON::PP::Boolean') ){ + return $$value == 1 ? 'true' : 'false'; + } + else { + if ((overload::StrVal($value) =~ /=(\w+)/)[0]) { + return $self->value_to_json("$value"); + } + + if ($type eq 'SCALAR' and defined $$value) { + return $$value eq '1' ? 'true' + : $$value eq '0' ? 'false' + : $self->{PROPS}->[ P_ALLOW_UNKNOWN ] ? 'null' + : encode_error("cannot encode reference to scalar"); + } + + if ( $self->{PROPS}->[ P_ALLOW_UNKNOWN ] ) { + return 'null'; + } + else { + if ( $type eq 'SCALAR' or $type eq 'REF' ) { + encode_error("cannot encode reference to scalar"); + } + else { + encode_error("encountered $value, but JSON can only represent references to arrays or hashes"); + } + } + + } + } + + + my %esc = ( + "\n" => '\n', + "\r" => '\r', + "\t" => '\t', + "\f" => '\f', + "\b" => '\b', + "\"" => '\"', + "\\" => '\\\\', + "\'" => '\\\'', + ); + + + sub string_to_json { + my ($self, $arg) = @_; + + $arg =~ s/([\x22\x5c\n\r\t\f\b])/$esc{$1}/g; + $arg =~ s/\//\\\//g if ($escape_slash); + $arg =~ s/([\x00-\x08\x0b\x0e-\x1f])/'\\u00' . unpack('H2', $1)/eg; + + if ($ascii) { + $arg = JSON_PP_encode_ascii($arg); + } + + if ($latin1) { + $arg = JSON_PP_encode_latin1($arg); + } + + if ($utf8) { + utf8::encode($arg); + } + + return '"' . $arg . '"'; + } + + + sub blessed_to_json { + my $reftype = reftype($_[1]) || ''; + if ($reftype eq 'HASH') { + return $_[0]->hash_to_json($_[1]); + } + elsif ($reftype eq 'ARRAY') { + return $_[0]->array_to_json($_[1]); + } + else { + return 'null'; + } + } + + + sub encode_error { + my $error = shift; + Carp::croak "$error"; + } + + + sub _sort { + defined $keysort ? (sort $keysort (keys %{$_[0]})) : keys %{$_[0]}; + } + + + sub _up_indent { + my $self = shift; + my $space = ' ' x $indent_length; + + my ($pre,$post) = ('',''); + + $post = "\n" . $space x $indent_count; + + $indent_count++; + + $pre = "\n" . $space x $indent_count; + + return ($pre,$post); + } + + + sub _down_indent { $indent_count--; } + + + sub PP_encode_box { + { + depth => $depth, + indent_count => $indent_count, + }; + } + +} # Convert + + +sub _encode_ascii { + join('', + map { + $_ <= 127 ? + chr($_) : + $_ <= 65535 ? + sprintf('\u%04x', $_) : sprintf('\u%x\u%x', _encode_surrogates($_)); + } unpack('U*', $_[0]) + ); +} + + +sub _encode_latin1 { + join('', + map { + $_ <= 255 ? + chr($_) : + $_ <= 65535 ? + sprintf('\u%04x', $_) : sprintf('\u%x\u%x', _encode_surrogates($_)); + } unpack('U*', $_[0]) + ); +} + + +sub _encode_surrogates { # from perlunicode + my $uni = $_[0] - 0x10000; + return ($uni / 0x400 + 0xD800, $uni % 0x400 + 0xDC00); +} + + +sub _is_bignum { + $_[0]->isa('Math::BigInt') or $_[0]->isa('Math::BigFloat'); +} + + + +# +# JSON => Perl +# + +my $max_intsize; + +BEGIN { + my $checkint = 1111; + for my $d (5..64) { + $checkint .= 1; + my $int = eval qq| $checkint |; + if ($int =~ /[eE]/) { + $max_intsize = $d - 1; + last; + } + } +} + +{ # PARSE + + my %escapes = ( # by Jeremy Muhlich <jmuhlich [at] bitflood.org> + b => "\x8", + t => "\x9", + n => "\xA", + f => "\xC", + r => "\xD", + '\\' => '\\', + '"' => '"', + '/' => '/', + ); + + my $text; # json data + my $at; # offset + my $ch; # first character + my $len; # text length (changed according to UTF8 or NON UTF8) + # INTERNAL + my $depth; # nest counter + my $encoding; # json text encoding + my $is_valid_utf8; # temp variable + my $utf8_len; # utf8 byte length + # FLAGS + my $utf8; # must be utf8 + my $max_depth; # max nest number of objects and arrays + my $max_size; + my $relaxed; + my $cb_object; + my $cb_sk_object; + + my $F_HOOK; + + my $allow_bignum; # using Math::BigInt/BigFloat + my $singlequote; # loosely quoting + my $loose; # + my $allow_barekey; # bareKey + my $allow_tags; + + my $alt_true; + my $alt_false; + + sub _detect_utf_encoding { + my $text = shift; + my @octets = unpack('C4', $text); + return 'unknown' unless defined $octets[3]; + return ( $octets[0] and $octets[1]) ? 'UTF-8' + : (!$octets[0] and $octets[1]) ? 'UTF-16BE' + : (!$octets[0] and !$octets[1]) ? 'UTF-32BE' + : ( $octets[2] ) ? 'UTF-16LE' + : (!$octets[2] ) ? 'UTF-32LE' + : 'unknown'; + } + + sub PP_decode_json { + my ($self, $want_offset); + + ($self, $text, $want_offset) = @_; + + ($at, $ch, $depth) = (0, '', 0); + + if ( !defined $text or ref $text ) { + decode_error("malformed JSON string, neither array, object, number, string or atom"); + } + + my $props = $self->{PROPS}; + + ($utf8, $relaxed, $loose, $allow_bignum, $allow_barekey, $singlequote, $allow_tags) + = @{$props}[P_UTF8, P_RELAXED, P_LOOSE .. P_ALLOW_SINGLEQUOTE, P_ALLOW_TAGS]; + + ($alt_true, $alt_false) = @$self{qw/true false/}; + + if ( $utf8 ) { + $encoding = _detect_utf_encoding($text); + if ($encoding ne 'UTF-8' and $encoding ne 'unknown') { + require Encode; + Encode::from_to($text, $encoding, 'utf-8'); + } else { + utf8::downgrade( $text, 1 ) or Carp::croak("Wide character in subroutine entry"); + } + } + else { + utf8::upgrade( $text ); + utf8::encode( $text ); + } + + $len = length $text; + + ($max_depth, $max_size, $cb_object, $cb_sk_object, $F_HOOK) + = @{$self}{qw/max_depth max_size cb_object cb_sk_object F_HOOK/}; + + if ($max_size > 1) { + use bytes; + my $bytes = length $text; + decode_error( + sprintf("attempted decode of JSON text of %s bytes size, but max_size is set to %s" + , $bytes, $max_size), 1 + ) if ($bytes > $max_size); + } + + white(); # remove head white space + + decode_error("malformed JSON string, neither array, object, number, string or atom") unless defined $ch; # Is there a first character for JSON structure? + + my $result = value(); + + if ( !$props->[ P_ALLOW_NONREF ] and !ref $result ) { + decode_error( + 'JSON text must be an object or array (but found number, string, true, false or null,' + . ' use allow_nonref to allow this)', 1); + } + + Carp::croak('something wrong.') if $len < $at; # we won't arrive here. + + my $consumed = defined $ch ? $at - 1 : $at; # consumed JSON text length + + white(); # remove tail white space + + return ( $result, $consumed ) if $want_offset; # all right if decode_prefix + + decode_error("garbage after JSON object") if defined $ch; + + $result; + } + + + sub next_chr { + return $ch = undef if($at >= $len); + $ch = substr($text, $at++, 1); + } + + + sub value { + white(); + return if(!defined $ch); + return object() if($ch eq '{'); + return array() if($ch eq '['); + return tag() if($ch eq '('); + return string() if($ch eq '"' or ($singlequote and $ch eq "'")); + return number() if($ch =~ /[0-9]/ or $ch eq '-'); + return word(); + } + + sub string { + my $utf16; + my $is_utf8; + + ($is_valid_utf8, $utf8_len) = ('', 0); + + my $s = ''; # basically UTF8 flag on + + if($ch eq '"' or ($singlequote and $ch eq "'")){ + my $boundChar = $ch; + + OUTER: while( defined(next_chr()) ){ + + if($ch eq $boundChar){ + next_chr(); + + if ($utf16) { + decode_error("missing low surrogate character in surrogate pair"); + } + + utf8::decode($s) if($is_utf8); + + return $s; + } + elsif($ch eq '\\'){ + next_chr(); + if(exists $escapes{$ch}){ + $s .= $escapes{$ch}; + } + elsif($ch eq 'u'){ # UNICODE handling + my $u = ''; + + for(1..4){ + $ch = next_chr(); + last OUTER if($ch !~ /[0-9a-fA-F]/); + $u .= $ch; + } + + # U+D800 - U+DBFF + if ($u =~ /^[dD][89abAB][0-9a-fA-F]{2}/) { # UTF-16 high surrogate? + $utf16 = $u; + } + # U+DC00 - U+DFFF + elsif ($u =~ /^[dD][c-fC-F][0-9a-fA-F]{2}/) { # UTF-16 low surrogate? + unless (defined $utf16) { + decode_error("missing high surrogate character in surrogate pair"); + } + $is_utf8 = 1; + $s .= JSON_PP_decode_surrogates($utf16, $u) || next; + $utf16 = undef; + } + else { + if (defined $utf16) { + decode_error("surrogate pair expected"); + } + + if ( ( my $hex = hex( $u ) ) > 127 ) { + $is_utf8 = 1; + $s .= JSON_PP_decode_unicode($u) || next; + } + else { + $s .= chr $hex; + } + } + + } + else{ + unless ($loose) { + $at -= 2; + decode_error('illegal backslash escape sequence in string'); + } + $s .= $ch; + } + } + else{ + + if ( ord $ch > 127 ) { + unless( $ch = is_valid_utf8($ch) ) { + $at -= 1; + decode_error("malformed UTF-8 character in JSON string"); + } + else { + $at += $utf8_len - 1; + } + + $is_utf8 = 1; + } + + if (!$loose) { + if ($ch =~ /[\x00-\x1f\x22\x5c]/) { # '/' ok + if (!$relaxed or $ch ne "\t") { + $at--; + decode_error('invalid character encountered while parsing JSON string'); + } + } + } + + $s .= $ch; + } + } + } + + decode_error("unexpected end of string while parsing JSON string"); + } + + + sub white { + while( defined $ch ){ + if($ch eq '' or $ch =~ /\A[ \t\r\n]\z/){ + next_chr(); + } + elsif($relaxed and $ch eq '/'){ + next_chr(); + if(defined $ch and $ch eq '/'){ + 1 while(defined(next_chr()) and $ch ne "\n" and $ch ne "\r"); + } + elsif(defined $ch and $ch eq '*'){ + next_chr(); + while(1){ + if(defined $ch){ + if($ch eq '*'){ + if(defined(next_chr()) and $ch eq '/'){ + next_chr(); + last; + } + } + else{ + next_chr(); + } + } + else{ + decode_error("Unterminated comment"); + } + } + next; + } + else{ + $at--; + decode_error("malformed JSON string, neither array, object, number, string or atom"); + } + } + else{ + if ($relaxed and $ch eq '#') { # correctly? + pos($text) = $at; + $text =~ /\G([^\n]*(?:\r\n|\r|\n|$))/g; + $at = pos($text); + next_chr; + next; + } + + last; + } + } + } + + + sub array { + my $a = $_[0] || []; # you can use this code to use another array ref object. + + decode_error('json text or perl structure exceeds maximum nesting level (max_depth set too low?)') + if (++$depth > $max_depth); + + next_chr(); + white(); + + if(defined $ch and $ch eq ']'){ + --$depth; + next_chr(); + return $a; + } + else { + while(defined($ch)){ + push @$a, value(); + + white(); + + if (!defined $ch) { + last; + } + + if($ch eq ']'){ + --$depth; + next_chr(); + return $a; + } + + if($ch ne ','){ + last; + } + + next_chr(); + white(); + + if ($relaxed and $ch eq ']') { + --$depth; + next_chr(); + return $a; + } + + } + } + + $at-- if defined $ch and $ch ne ''; + decode_error(", or ] expected while parsing array"); + } + + sub tag { + decode_error('malformed JSON string, neither array, object, number, string or atom') unless $allow_tags; + + next_chr(); + white(); + + my $tag = value(); + return unless defined $tag; + decode_error('malformed JSON string, (tag) must be a string') if ref $tag; + + white(); + + if (!defined $ch or $ch ne ')') { + decode_error(') expected after tag'); + } + + next_chr(); + white(); + + my $val = value(); + return unless defined $val; + decode_error('malformed JSON string, tag value must be an array') unless ref $val eq 'ARRAY'; + + if (!eval { $tag->can('THAW') }) { + decode_error('cannot decode perl-object (package does not exist)') if $@; + decode_error('cannot decode perl-object (package does not have a THAW method)'); + } + $tag->THAW('JSON', @$val); + } + + sub object { + my $o = $_[0] || {}; # you can use this code to use another hash ref object. + my $k; + + decode_error('json text or perl structure exceeds maximum nesting level (max_depth set too low?)') + if (++$depth > $max_depth); + next_chr(); + white(); + + if(defined $ch and $ch eq '}'){ + --$depth; + next_chr(); + if ($F_HOOK) { + return _json_object_hook($o); + } + return $o; + } + else { + while (defined $ch) { + $k = ($allow_barekey and $ch ne '"' and $ch ne "'") ? bareKey() : string(); + white(); + + if(!defined $ch or $ch ne ':'){ + $at--; + decode_error("':' expected"); + } + + next_chr(); + $o->{$k} = value(); + white(); + + last if (!defined $ch); + + if($ch eq '}'){ + --$depth; + next_chr(); + if ($F_HOOK) { + return _json_object_hook($o); + } + return $o; + } + + if($ch ne ','){ + last; + } + + next_chr(); + white(); + + if ($relaxed and $ch eq '}') { + --$depth; + next_chr(); + if ($F_HOOK) { + return _json_object_hook($o); + } + return $o; + } + + } + + } + + $at-- if defined $ch and $ch ne ''; + decode_error(", or } expected while parsing object/hash"); + } + + + sub bareKey { # doesn't strictly follow Standard ECMA-262 3rd Edition + my $key; + while($ch =~ /[^\x00-\x23\x25-\x2F\x3A-\x40\x5B-\x5E\x60\x7B-\x7F]/){ + $key .= $ch; + next_chr(); + } + return $key; + } + + + sub word { + my $word = substr($text,$at-1,4); + + if($word eq 'true'){ + $at += 3; + next_chr; + return defined $alt_true ? $alt_true : $JSON::PP::true; + } + elsif($word eq 'null'){ + $at += 3; + next_chr; + return undef; + } + elsif($word eq 'fals'){ + $at += 3; + if(substr($text,$at,1) eq 'e'){ + $at++; + next_chr; + return defined $alt_false ? $alt_false : $JSON::PP::false; + } + } + + $at--; # for decode_error report + + decode_error("'null' expected") if ($word =~ /^n/); + decode_error("'true' expected") if ($word =~ /^t/); + decode_error("'false' expected") if ($word =~ /^f/); + decode_error("malformed JSON string, neither array, object, number, string or atom"); + } + + + sub number { + my $n = ''; + my $v; + my $is_dec; + my $is_exp; + + if($ch eq '-'){ + $n = '-'; + next_chr; + if (!defined $ch or $ch !~ /\d/) { + decode_error("malformed number (no digits after initial minus)"); + } + } + + # According to RFC4627, hex or oct digits are invalid. + if($ch eq '0'){ + my $peek = substr($text,$at,1); + if($peek =~ /^[0-9a-dfA-DF]/){ # e may be valid (exponential) + decode_error("malformed number (leading zero must not be followed by another digit)"); + } + $n .= $ch; + next_chr; + } + + while(defined $ch and $ch =~ /\d/){ + $n .= $ch; + next_chr; + } + + if(defined $ch and $ch eq '.'){ + $n .= '.'; + $is_dec = 1; + + next_chr; + if (!defined $ch or $ch !~ /\d/) { + decode_error("malformed number (no digits after decimal point)"); + } + else { + $n .= $ch; + } + + while(defined(next_chr) and $ch =~ /\d/){ + $n .= $ch; + } + } + + if(defined $ch and ($ch eq 'e' or $ch eq 'E')){ + $n .= $ch; + $is_exp = 1; + next_chr; + + if(defined($ch) and ($ch eq '+' or $ch eq '-')){ + $n .= $ch; + next_chr; + if (!defined $ch or $ch =~ /\D/) { + decode_error("malformed number (no digits after exp sign)"); + } + $n .= $ch; + } + elsif(defined($ch) and $ch =~ /\d/){ + $n .= $ch; + } + else { + decode_error("malformed number (no digits after exp sign)"); + } + + while(defined(next_chr) and $ch =~ /\d/){ + $n .= $ch; + } + + } + + $v .= $n; + + if ($is_dec or $is_exp) { + if ($allow_bignum) { + require Math::BigFloat; + return Math::BigFloat->new($v); + } + } else { + if (length $v > $max_intsize) { + if ($allow_bignum) { # from Adam Sussman + require Math::BigInt; + return Math::BigInt->new($v); + } + else { + return "$v"; + } + } + } + + return $is_dec ? $v/1.0 : 0+$v; + } + + + sub is_valid_utf8 { + + $utf8_len = $_[0] =~ /[\x00-\x7F]/ ? 1 + : $_[0] =~ /[\xC2-\xDF]/ ? 2 + : $_[0] =~ /[\xE0-\xEF]/ ? 3 + : $_[0] =~ /[\xF0-\xF4]/ ? 4 + : 0 + ; + + return unless $utf8_len; + + my $is_valid_utf8 = substr($text, $at - 1, $utf8_len); + + return ( $is_valid_utf8 =~ /^(?: + [\x00-\x7F] + |[\xC2-\xDF][\x80-\xBF] + |[\xE0][\xA0-\xBF][\x80-\xBF] + |[\xE1-\xEC][\x80-\xBF][\x80-\xBF] + |[\xED][\x80-\x9F][\x80-\xBF] + |[\xEE-\xEF][\x80-\xBF][\x80-\xBF] + |[\xF0][\x90-\xBF][\x80-\xBF][\x80-\xBF] + |[\xF1-\xF3][\x80-\xBF][\x80-\xBF][\x80-\xBF] + |[\xF4][\x80-\x8F][\x80-\xBF][\x80-\xBF] + )$/x ) ? $is_valid_utf8 : ''; + } + + + sub decode_error { + my $error = shift; + my $no_rep = shift; + my $str = defined $text ? substr($text, $at) : ''; + my $mess = ''; + my $type = 'U*'; + + if ( OLD_PERL ) { + my $type = $] < 5.006 ? 'C*' + : utf8::is_utf8( $str ) ? 'U*' # 5.6 + : 'C*' + ; + } + + for my $c ( unpack( $type, $str ) ) { # emulate pv_uni_display() ? + $mess .= $c == 0x07 ? '\a' + : $c == 0x09 ? '\t' + : $c == 0x0a ? '\n' + : $c == 0x0d ? '\r' + : $c == 0x0c ? '\f' + : $c < 0x20 ? sprintf('\x{%x}', $c) + : $c == 0x5c ? '\\\\' + : $c < 0x80 ? chr($c) + : sprintf('\x{%x}', $c) + ; + if ( length $mess >= 20 ) { + $mess .= '...'; + last; + } + } + + unless ( length $mess ) { + $mess = '(end of string)'; + } + + Carp::croak ( + $no_rep ? "$error" : "$error, at character offset $at (before \"$mess\")" + ); + + } + + + sub _json_object_hook { + my $o = $_[0]; + my @ks = keys %{$o}; + + if ( $cb_sk_object and @ks == 1 and exists $cb_sk_object->{ $ks[0] } and ref $cb_sk_object->{ $ks[0] } ) { + my @val = $cb_sk_object->{ $ks[0] }->( $o->{$ks[0]} ); + if (@val == 0) { + return $o; + } + elsif (@val == 1) { + return $val[0]; + } + else { + Carp::croak("filter_json_single_key_object callbacks must not return more than one scalar"); + } + } + + my @val = $cb_object->($o) if ($cb_object); + if (@val == 0) { + return $o; + } + elsif (@val == 1) { + return $val[0]; + } + else { + Carp::croak("filter_json_object callbacks must not return more than one scalar"); + } + } + + + sub PP_decode_box { + { + text => $text, + at => $at, + ch => $ch, + len => $len, + depth => $depth, + encoding => $encoding, + is_valid_utf8 => $is_valid_utf8, + }; + } + +} # PARSE + + +sub _decode_surrogates { # from perlunicode + my $uni = 0x10000 + (hex($_[0]) - 0xD800) * 0x400 + (hex($_[1]) - 0xDC00); + my $un = pack('U*', $uni); + utf8::encode( $un ); + return $un; +} + + +sub _decode_unicode { + my $un = pack('U', hex shift); + utf8::encode( $un ); + return $un; +} + +# +# Setup for various Perl versions (the code from JSON::PP58) +# + +BEGIN { + + unless ( defined &utf8::is_utf8 ) { + require Encode; + *utf8::is_utf8 = *Encode::is_utf8; + } + + if ( !OLD_PERL ) { + *JSON::PP::JSON_PP_encode_ascii = \&_encode_ascii; + *JSON::PP::JSON_PP_encode_latin1 = \&_encode_latin1; + *JSON::PP::JSON_PP_decode_surrogates = \&_decode_surrogates; + *JSON::PP::JSON_PP_decode_unicode = \&_decode_unicode; + + if ($] < 5.008003) { # join() in 5.8.0 - 5.8.2 is broken. + package # hide from PAUSE + JSON::PP; + require subs; + subs->import('join'); + eval q| + sub join { + return '' if (@_ < 2); + my $j = shift; + my $str = shift; + for (@_) { $str .= $j . $_; } + return $str; + } + |; + } + } + + + sub JSON::PP::incr_parse { + local $Carp::CarpLevel = 1; + ( $_[0]->{_incr_parser} ||= JSON::PP::IncrParser->new )->incr_parse( @_ ); + } + + + sub JSON::PP::incr_skip { + ( $_[0]->{_incr_parser} ||= JSON::PP::IncrParser->new )->incr_skip; + } + + + sub JSON::PP::incr_reset { + ( $_[0]->{_incr_parser} ||= JSON::PP::IncrParser->new )->incr_reset; + } + + eval q{ + sub JSON::PP::incr_text : lvalue { + $_[0]->{_incr_parser} ||= JSON::PP::IncrParser->new; + + if ( $_[0]->{_incr_parser}->{incr_pos} ) { + Carp::croak("incr_text cannot be called when the incremental parser already started parsing"); + } + $_[0]->{_incr_parser}->{incr_text}; + } + } if ( $] >= 5.006 ); + +} # Setup for various Perl versions (the code from JSON::PP58) + + +############################### +# Utilities +# + +BEGIN { + eval 'require Scalar::Util'; + unless($@){ + *JSON::PP::blessed = \&Scalar::Util::blessed; + *JSON::PP::reftype = \&Scalar::Util::reftype; + *JSON::PP::refaddr = \&Scalar::Util::refaddr; + } + else{ # This code is from Scalar::Util. + # warn $@; + eval 'sub UNIVERSAL::a_sub_not_likely_to_be_here { ref($_[0]) }'; + *JSON::PP::blessed = sub { + local($@, $SIG{__DIE__}, $SIG{__WARN__}); + ref($_[0]) ? eval { $_[0]->a_sub_not_likely_to_be_here } : undef; + }; + require B; + my %tmap = qw( + B::NULL SCALAR + B::HV HASH + B::AV ARRAY + B::CV CODE + B::IO IO + B::GV GLOB + B::REGEXP REGEXP + ); + *JSON::PP::reftype = sub { + my $r = shift; + + return undef unless length(ref($r)); + + my $t = ref(B::svref_2object($r)); + + return + exists $tmap{$t} ? $tmap{$t} + : length(ref($$r)) ? 'REF' + : 'SCALAR'; + }; + *JSON::PP::refaddr = sub { + return undef unless length(ref($_[0])); + + my $addr; + if(defined(my $pkg = blessed($_[0]))) { + $addr .= bless $_[0], 'Scalar::Util::Fake'; + bless $_[0], $pkg; + } + else { + $addr .= $_[0] + } + + $addr =~ /0x(\w+)/; + local $^W; + #no warnings 'portable'; + hex($1); + } + } +} + + +# shamelessly copied and modified from JSON::XS code. + +$JSON::PP::true = do { bless \(my $dummy = 1), "JSON::PP::Boolean" }; +$JSON::PP::false = do { bless \(my $dummy = 0), "JSON::PP::Boolean" }; + +sub is_bool { blessed $_[0] and ( $_[0]->isa("JSON::PP::Boolean") or $_[0]->isa("Types::Serialiser::BooleanBase") or $_[0]->isa("JSON::XS::Boolean") ); } + +sub true { $JSON::PP::true } +sub false { $JSON::PP::false } +sub null { undef; } + +############################### + +package # hide from PAUSE + JSON::PP::IncrParser; + +use strict; + +use constant INCR_M_WS => 0; # initial whitespace skipping +use constant INCR_M_STR => 1; # inside string +use constant INCR_M_BS => 2; # inside backslash +use constant INCR_M_JSON => 3; # outside anything, count nesting +use constant INCR_M_C0 => 4; +use constant INCR_M_C1 => 5; +use constant INCR_M_TFN => 6; +use constant INCR_M_NUM => 7; + +$JSON::backportPP::IncrParser::VERSION = '1.01'; + +sub new { + my ( $class ) = @_; + + bless { + incr_nest => 0, + incr_text => undef, + incr_pos => 0, + incr_mode => 0, + }, $class; +} + + +sub incr_parse { + my ( $self, $coder, $text ) = @_; + + $self->{incr_text} = '' unless ( defined $self->{incr_text} ); + + if ( defined $text ) { + if ( utf8::is_utf8( $text ) and !utf8::is_utf8( $self->{incr_text} ) ) { + utf8::upgrade( $self->{incr_text} ) ; + utf8::decode( $self->{incr_text} ) ; + } + $self->{incr_text} .= $text; + } + + if ( defined wantarray ) { + my $max_size = $coder->get_max_size; + my $p = $self->{incr_pos}; + my @ret; + { + do { + unless ( $self->{incr_nest} <= 0 and $self->{incr_mode} == INCR_M_JSON ) { + $self->_incr_parse( $coder ); + + if ( $max_size and $self->{incr_pos} > $max_size ) { + Carp::croak("attempted decode of JSON text of $self->{incr_pos} bytes size, but max_size is set to $max_size"); + } + unless ( $self->{incr_nest} <= 0 and $self->{incr_mode} == INCR_M_JSON ) { + # as an optimisation, do not accumulate white space in the incr buffer + if ( $self->{incr_mode} == INCR_M_WS and $self->{incr_pos} ) { + $self->{incr_pos} = 0; + $self->{incr_text} = ''; + } + last; + } + } + + my ($obj, $offset) = $coder->PP_decode_json( $self->{incr_text}, 0x00000001 ); + push @ret, $obj; + use bytes; + $self->{incr_text} = substr( $self->{incr_text}, $offset || 0 ); + $self->{incr_pos} = 0; + $self->{incr_nest} = 0; + $self->{incr_mode} = 0; + last unless wantarray; + } while ( wantarray ); + } + + if ( wantarray ) { + return @ret; + } + else { # in scalar context + return defined $ret[0] ? $ret[0] : undef; + } + } +} + + +sub _incr_parse { + my ($self, $coder) = @_; + my $text = $self->{incr_text}; + my $len = length $text; + my $p = $self->{incr_pos}; + +INCR_PARSE: + while ( $len > $p ) { + my $s = substr( $text, $p, 1 ); + last INCR_PARSE unless defined $s; + my $mode = $self->{incr_mode}; + + if ( $mode == INCR_M_WS ) { + while ( $len > $p ) { + $s = substr( $text, $p, 1 ); + last INCR_PARSE unless defined $s; + if ( ord($s) > 0x20 ) { + if ( $s eq '#' ) { + $self->{incr_mode} = INCR_M_C0; + redo INCR_PARSE; + } else { + $self->{incr_mode} = INCR_M_JSON; + redo INCR_PARSE; + } + } + $p++; + } + } elsif ( $mode == INCR_M_BS ) { + $p++; + $self->{incr_mode} = INCR_M_STR; + redo INCR_PARSE; + } elsif ( $mode == INCR_M_C0 or $mode == INCR_M_C1 ) { + while ( $len > $p ) { + $s = substr( $text, $p, 1 ); + last INCR_PARSE unless defined $s; + if ( $s eq "\n" ) { + $self->{incr_mode} = $self->{incr_mode} == INCR_M_C0 ? INCR_M_WS : INCR_M_JSON; + last; + } + $p++; + } + next; + } elsif ( $mode == INCR_M_TFN ) { + while ( $len > $p ) { + $s = substr( $text, $p++, 1 ); + next if defined $s and $s =~ /[rueals]/; + last; + } + $p--; + $self->{incr_mode} = INCR_M_JSON; + + last INCR_PARSE unless $self->{incr_nest}; + redo INCR_PARSE; + } elsif ( $mode == INCR_M_NUM ) { + while ( $len > $p ) { + $s = substr( $text, $p++, 1 ); + next if defined $s and $s =~ /[0-9eE.+\-]/; + last; + } + $p--; + $self->{incr_mode} = INCR_M_JSON; + + last INCR_PARSE unless $self->{incr_nest}; + redo INCR_PARSE; + } elsif ( $mode == INCR_M_STR ) { + while ( $len > $p ) { + $s = substr( $text, $p, 1 ); + last INCR_PARSE unless defined $s; + if ( $s eq '"' ) { + $p++; + $self->{incr_mode} = INCR_M_JSON; + + last INCR_PARSE unless $self->{incr_nest}; + redo INCR_PARSE; + } + elsif ( $s eq '\\' ) { + $p++; + if ( !defined substr($text, $p, 1) ) { + $self->{incr_mode} = INCR_M_BS; + last INCR_PARSE; + } + } + $p++; + } + } elsif ( $mode == INCR_M_JSON ) { + while ( $len > $p ) { + $s = substr( $text, $p++, 1 ); + if ( $s eq "\x00" ) { + $p--; + last INCR_PARSE; + } elsif ( $s eq "\x09" or $s eq "\x0a" or $s eq "\x0d" or $s eq "\x20" ) { + if ( !$self->{incr_nest} ) { + $p--; # do not eat the whitespace, let the next round do it + last INCR_PARSE; + } + next; + } elsif ( $s eq 't' or $s eq 'f' or $s eq 'n' ) { + $self->{incr_mode} = INCR_M_TFN; + redo INCR_PARSE; + } elsif ( $s =~ /^[0-9\-]$/ ) { + $self->{incr_mode} = INCR_M_NUM; + redo INCR_PARSE; + } elsif ( $s eq '"' ) { + $self->{incr_mode} = INCR_M_STR; + redo INCR_PARSE; + } elsif ( $s eq '[' or $s eq '{' ) { + if ( ++$self->{incr_nest} > $coder->get_max_depth ) { + Carp::croak('json text or perl structure exceeds maximum nesting level (max_depth set too low?)'); + } + next; + } elsif ( $s eq ']' or $s eq '}' ) { + if ( --$self->{incr_nest} <= 0 ) { + last INCR_PARSE; + } + } elsif ( $s eq '#' ) { + $self->{incr_mode} = INCR_M_C1; + redo INCR_PARSE; + } + } + } + } + + $self->{incr_pos} = $p; + $self->{incr_parsing} = $p ? 1 : 0; # for backward compatibility +} + + +sub incr_text { + if ( $_[0]->{incr_pos} ) { + Carp::croak("incr_text cannot be called when the incremental parser already started parsing"); + } + $_[0]->{incr_text}; +} + + +sub incr_skip { + my $self = shift; + $self->{incr_text} = substr( $self->{incr_text}, $self->{incr_pos} ); + $self->{incr_pos} = 0; + $self->{incr_mode} = 0; + $self->{incr_nest} = 0; +} + + +sub incr_reset { + my $self = shift; + $self->{incr_text} = undef; + $self->{incr_pos} = 0; + $self->{incr_mode} = 0; + $self->{incr_nest} = 0; +} + +############################### + + +1; +__END__ +=pod + +=head1 NAME + +JSON::PP - JSON::XS compatible pure-Perl module. + +=head1 SYNOPSIS + + use JSON::PP; + + # exported functions, they croak on error + # and expect/generate UTF-8 + + $utf8_encoded_json_text = encode_json $perl_hash_or_arrayref; + $perl_hash_or_arrayref = decode_json $utf8_encoded_json_text; + + # OO-interface + + $json = JSON::PP->new->ascii->pretty->allow_nonref; + + $pretty_printed_json_text = $json->encode( $perl_scalar ); + $perl_scalar = $json->decode( $json_text ); + + # Note that JSON version 2.0 and above will automatically use + # JSON::XS or JSON::PP, so you should be able to just: + + use JSON; + + +=head1 VERSION + + 4.02 + +=head1 DESCRIPTION + +JSON::PP is a pure perl JSON decoder/encoder, and (almost) compatible to much +faster L<JSON::XS> written by Marc Lehmann in C. JSON::PP works as +a fallback module when you use L<JSON> module without having +installed JSON::XS. + +Because of this fallback feature of JSON.pm, JSON::PP tries not to +be more JavaScript-friendly than JSON::XS (i.e. not to escape extra +characters such as U+2028 and U+2029, etc), +in order for you not to lose such JavaScript-friendliness silently +when you use JSON.pm and install JSON::XS for speed or by accident. +If you need JavaScript-friendly RFC7159-compliant pure perl module, +try L<JSON::Tiny>, which is derived from L<Mojolicious> web +framework and is also smaller and faster than JSON::PP. + +JSON::PP has been in the Perl core since Perl 5.14, mainly for +CPAN toolchain modules to parse META.json. + +=head1 FUNCTIONAL INTERFACE + +This section is taken from JSON::XS almost verbatim. C<encode_json> +and C<decode_json> are exported by default. + +=head2 encode_json + + $json_text = encode_json $perl_scalar + +Converts the given Perl data structure to a UTF-8 encoded, binary string +(that is, the string contains octets only). Croaks on error. + +This function call is functionally identical to: + + $json_text = JSON::PP->new->utf8->encode($perl_scalar) + +Except being faster. + +=head2 decode_json + + $perl_scalar = decode_json $json_text + +The opposite of C<encode_json>: expects an UTF-8 (binary) string and tries +to parse that as an UTF-8 encoded JSON text, returning the resulting +reference. Croaks on error. + +This function call is functionally identical to: + + $perl_scalar = JSON::PP->new->utf8->decode($json_text) + +Except being faster. + +=head2 JSON::PP::is_bool + + $is_boolean = JSON::PP::is_bool($scalar) + +Returns true if the passed scalar represents either JSON::PP::true or +JSON::PP::false, two constants that act like C<1> and C<0> respectively +and are also used to represent JSON C<true> and C<false> in Perl strings. + +See L<MAPPING>, below, for more information on how JSON values are mapped to +Perl. + +=head1 OBJECT-ORIENTED INTERFACE + +This section is also taken from JSON::XS. + +The object oriented interface lets you configure your own encoding or +decoding style, within the limits of supported formats. + +=head2 new + + $json = JSON::PP->new + +Creates a new JSON::PP object that can be used to de/encode JSON +strings. All boolean flags described below are by default I<disabled> +(with the exception of C<allow_nonref>, which defaults to I<enabled> since +version C<4.0>). + +The mutators for flags all return the JSON::PP object again and thus calls can +be chained: + + my $json = JSON::PP->new->utf8->space_after->encode({a => [1,2]}) + => {"a": [1, 2]} + +=head2 ascii + + $json = $json->ascii([$enable]) + + $enabled = $json->get_ascii + +If C<$enable> is true (or missing), then the C<encode> method will not +generate characters outside the code range C<0..127> (which is ASCII). Any +Unicode characters outside that range will be escaped using either a +single \uXXXX (BMP characters) or a double \uHHHH\uLLLLL escape sequence, +as per RFC4627. The resulting encoded JSON text can be treated as a native +Unicode string, an ascii-encoded, latin1-encoded or UTF-8 encoded string, +or any other superset of ASCII. + +If C<$enable> is false, then the C<encode> method will not escape Unicode +characters unless required by the JSON syntax or other flags. This results +in a faster and more compact format. + +See also the section I<ENCODING/CODESET FLAG NOTES> later in this document. + +The main use for this flag is to produce JSON texts that can be +transmitted over a 7-bit channel, as the encoded JSON texts will not +contain any 8 bit characters. + + JSON::PP->new->ascii(1)->encode([chr 0x10401]) + => ["\ud801\udc01"] + +=head2 latin1 + + $json = $json->latin1([$enable]) + + $enabled = $json->get_latin1 + +If C<$enable> is true (or missing), then the C<encode> method will encode +the resulting JSON text as latin1 (or iso-8859-1), escaping any characters +outside the code range C<0..255>. The resulting string can be treated as a +latin1-encoded JSON text or a native Unicode string. The C<decode> method +will not be affected in any way by this flag, as C<decode> by default +expects Unicode, which is a strict superset of latin1. + +If C<$enable> is false, then the C<encode> method will not escape Unicode +characters unless required by the JSON syntax or other flags. + +See also the section I<ENCODING/CODESET FLAG NOTES> later in this document. + +The main use for this flag is efficiently encoding binary data as JSON +text, as most octets will not be escaped, resulting in a smaller encoded +size. The disadvantage is that the resulting JSON text is encoded +in latin1 (and must correctly be treated as such when storing and +transferring), a rare encoding for JSON. It is therefore most useful when +you want to store data structures known to contain binary data efficiently +in files or databases, not when talking to other JSON encoders/decoders. + + JSON::PP->new->latin1->encode (["\x{89}\x{abc}"] + => ["\x{89}\\u0abc"] # (perl syntax, U+abc escaped, U+89 not) + +=head2 utf8 + + $json = $json->utf8([$enable]) + + $enabled = $json->get_utf8 + +If C<$enable> is true (or missing), then the C<encode> method will encode +the JSON result into UTF-8, as required by many protocols, while the +C<decode> method expects to be handled an UTF-8-encoded string. Please +note that UTF-8-encoded strings do not contain any characters outside the +range C<0..255>, they are thus useful for bytewise/binary I/O. In future +versions, enabling this option might enable autodetection of the UTF-16 +and UTF-32 encoding families, as described in RFC4627. + +If C<$enable> is false, then the C<encode> method will return the JSON +string as a (non-encoded) Unicode string, while C<decode> expects thus a +Unicode string. Any decoding or encoding (e.g. to UTF-8 or UTF-16) needs +to be done yourself, e.g. using the Encode module. + +See also the section I<ENCODING/CODESET FLAG NOTES> later in this document. + +Example, output UTF-16BE-encoded JSON: + + use Encode; + $jsontext = encode "UTF-16BE", JSON::PP->new->encode ($object); + +Example, decode UTF-32LE-encoded JSON: + + use Encode; + $object = JSON::PP->new->decode (decode "UTF-32LE", $jsontext); + +=head2 pretty + + $json = $json->pretty([$enable]) + +This enables (or disables) all of the C<indent>, C<space_before> and +C<space_after> (and in the future possibly more) flags in one call to +generate the most readable (or most compact) form possible. + +=head2 indent + + $json = $json->indent([$enable]) + + $enabled = $json->get_indent + +If C<$enable> is true (or missing), then the C<encode> method will use a multiline +format as output, putting every array member or object/hash key-value pair +into its own line, indenting them properly. + +If C<$enable> is false, no newlines or indenting will be produced, and the +resulting JSON text is guaranteed not to contain any C<newlines>. + +This setting has no effect when decoding JSON texts. + +The default indent space length is three. +You can use C<indent_length> to change the length. + +=head2 space_before + + $json = $json->space_before([$enable]) + + $enabled = $json->get_space_before + +If C<$enable> is true (or missing), then the C<encode> method will add an extra +optional space before the C<:> separating keys from values in JSON objects. + +If C<$enable> is false, then the C<encode> method will not add any extra +space at those places. + +This setting has no effect when decoding JSON texts. You will also +most likely combine this setting with C<space_after>. + +Example, space_before enabled, space_after and indent disabled: + + {"key" :"value"} + +=head2 space_after + + $json = $json->space_after([$enable]) + + $enabled = $json->get_space_after + +If C<$enable> is true (or missing), then the C<encode> method will add an extra +optional space after the C<:> separating keys from values in JSON objects +and extra whitespace after the C<,> separating key-value pairs and array +members. + +If C<$enable> is false, then the C<encode> method will not add any extra +space at those places. + +This setting has no effect when decoding JSON texts. + +Example, space_before and indent disabled, space_after enabled: + + {"key": "value"} + +=head2 relaxed + + $json = $json->relaxed([$enable]) + + $enabled = $json->get_relaxed + +If C<$enable> is true (or missing), then C<decode> will accept some +extensions to normal JSON syntax (see below). C<encode> will not be +affected in anyway. I<Be aware that this option makes you accept invalid +JSON texts as if they were valid!>. I suggest only to use this option to +parse application-specific files written by humans (configuration files, +resource files etc.) + +If C<$enable> is false (the default), then C<decode> will only accept +valid JSON texts. + +Currently accepted extensions are: + +=over 4 + +=item * list items can have an end-comma + +JSON I<separates> array elements and key-value pairs with commas. This +can be annoying if you write JSON texts manually and want to be able to +quickly append elements, so this extension accepts comma at the end of +such items not just between them: + + [ + 1, + 2, <- this comma not normally allowed + ] + { + "k1": "v1", + "k2": "v2", <- this comma not normally allowed + } + +=item * shell-style '#'-comments + +Whenever JSON allows whitespace, shell-style comments are additionally +allowed. They are terminated by the first carriage-return or line-feed +character, after which more white-space and comments are allowed. + + [ + 1, # this comment not allowed in JSON + # neither this one... + ] + +=item * C-style multiple-line '/* */'-comments (JSON::PP only) + +Whenever JSON allows whitespace, C-style multiple-line comments are additionally +allowed. Everything between C</*> and C<*/> is a comment, after which +more white-space and comments are allowed. + + [ + 1, /* this comment not allowed in JSON */ + /* neither this one... */ + ] + +=item * C++-style one-line '//'-comments (JSON::PP only) + +Whenever JSON allows whitespace, C++-style one-line comments are additionally +allowed. They are terminated by the first carriage-return or line-feed +character, after which more white-space and comments are allowed. + + [ + 1, // this comment not allowed in JSON + // neither this one... + ] + +=item * literal ASCII TAB characters in strings + +Literal ASCII TAB characters are now allowed in strings (and treated as +C<\t>). + + [ + "Hello\tWorld", + "Hello<TAB>World", # literal <TAB> would not normally be allowed + ] + +=back + +=head2 canonical + + $json = $json->canonical([$enable]) + + $enabled = $json->get_canonical + +If C<$enable> is true (or missing), then the C<encode> method will output JSON objects +by sorting their keys. This is adding a comparatively high overhead. + +If C<$enable> is false, then the C<encode> method will output key-value +pairs in the order Perl stores them (which will likely change between runs +of the same script, and can change even within the same run from 5.18 +onwards). + +This option is useful if you want the same data structure to be encoded as +the same JSON text (given the same overall settings). If it is disabled, +the same hash might be encoded differently even if contains the same data, +as key-value pairs have no inherent ordering in Perl. + +This setting has no effect when decoding JSON texts. + +This setting has currently no effect on tied hashes. + +=head2 allow_nonref + + $json = $json->allow_nonref([$enable]) + + $enabled = $json->get_allow_nonref + +Unlike other boolean options, this opotion is enabled by default beginning +with version C<4.0>. + +If C<$enable> is true (or missing), then the C<encode> method can convert a +non-reference into its corresponding string, number or null JSON value, +which is an extension to RFC4627. Likewise, C<decode> will accept those JSON +values instead of croaking. + +If C<$enable> is false, then the C<encode> method will croak if it isn't +passed an arrayref or hashref, as JSON texts must either be an object +or array. Likewise, C<decode> will croak if given something that is not a +JSON object or array. + +Example, encode a Perl scalar as JSON value without enabled C<allow_nonref>, +resulting in an error: + + JSON::PP->new->allow_nonref(0)->encode ("Hello, World!") + => hash- or arrayref expected... + +=head2 allow_unknown + + $json = $json->allow_unknown([$enable]) + + $enabled = $json->get_allow_unknown + +If C<$enable> is true (or missing), then C<encode> will I<not> throw an +exception when it encounters values it cannot represent in JSON (for +example, filehandles) but instead will encode a JSON C<null> value. Note +that blessed objects are not included here and are handled separately by +c<allow_blessed>. + +If C<$enable> is false (the default), then C<encode> will throw an +exception when it encounters anything it cannot encode as JSON. + +This option does not affect C<decode> in any way, and it is recommended to +leave it off unless you know your communications partner. + +=head2 allow_blessed + + $json = $json->allow_blessed([$enable]) + + $enabled = $json->get_allow_blessed + +See L<OBJECT SERIALISATION> for details. + +If C<$enable> is true (or missing), then the C<encode> method will not +barf when it encounters a blessed reference that it cannot convert +otherwise. Instead, a JSON C<null> value is encoded instead of the object. + +If C<$enable> is false (the default), then C<encode> will throw an +exception when it encounters a blessed object that it cannot convert +otherwise. + +This setting has no effect on C<decode>. + +=head2 convert_blessed + + $json = $json->convert_blessed([$enable]) + + $enabled = $json->get_convert_blessed + +See L<OBJECT SERIALISATION> for details. + +If C<$enable> is true (or missing), then C<encode>, upon encountering a +blessed object, will check for the availability of the C<TO_JSON> method +on the object's class. If found, it will be called in scalar context and +the resulting scalar will be encoded instead of the object. + +The C<TO_JSON> method may safely call die if it wants. If C<TO_JSON> +returns other blessed objects, those will be handled in the same +way. C<TO_JSON> must take care of not causing an endless recursion cycle +(== crash) in this case. The name of C<TO_JSON> was chosen because other +methods called by the Perl core (== not by the user of the object) are +usually in upper case letters and to avoid collisions with any C<to_json> +function or method. + +If C<$enable> is false (the default), then C<encode> will not consider +this type of conversion. + +This setting has no effect on C<decode>. + +=head2 allow_tags + + $json = $json->allow_tags([$enable]) + + $enabled = $json->get_allow_tags + +See L<OBJECT SERIALISATION> for details. + +If C<$enable> is true (or missing), then C<encode>, upon encountering a +blessed object, will check for the availability of the C<FREEZE> method on +the object's class. If found, it will be used to serialise the object into +a nonstandard tagged JSON value (that JSON decoders cannot decode). + +It also causes C<decode> to parse such tagged JSON values and deserialise +them via a call to the C<THAW> method. + +If C<$enable> is false (the default), then C<encode> will not consider +this type of conversion, and tagged JSON values will cause a parse error +in C<decode>, as if tags were not part of the grammar. + +=head2 boolean_values + + $json->boolean_values([$false, $true]) + + ($false, $true) = $json->get_boolean_values + +By default, JSON booleans will be decoded as overloaded +C<$JSON::PP::false> and C<$JSON::PP::true> objects. + +With this method you can specify your own boolean values for decoding - +on decode, JSON C<false> will be decoded as a copy of C<$false>, and JSON +C<true> will be decoded as C<$true> ("copy" here is the same thing as +assigning a value to another variable, i.e. C<$copy = $false>). + +This is useful when you want to pass a decoded data structure directly +to other serialisers like YAML, Data::MessagePack and so on. + +Note that this works only when you C<decode>. You can set incompatible +boolean objects (like L<boolean>), but when you C<encode> a data structure +with such boolean objects, you still need to enable C<convert_blessed> +(and add a C<TO_JSON> method if necessary). + +Calling this method without any arguments will reset the booleans +to their default values. + +C<get_boolean_values> will return both C<$false> and C<$true> values, or +the empty list when they are set to the default. + +=head2 filter_json_object + + $json = $json->filter_json_object([$coderef]) + +When C<$coderef> is specified, it will be called from C<decode> each +time it decodes a JSON object. The only argument is a reference to +the newly-created hash. If the code references returns a single scalar +(which need not be a reference), this value (or rather a copy of it) is +inserted into the deserialised data structure. If it returns an empty +list (NOTE: I<not> C<undef>, which is a valid scalar), the original +deserialised hash will be inserted. This setting can slow down decoding +considerably. + +When C<$coderef> is omitted or undefined, any existing callback will +be removed and C<decode> will not change the deserialised hash in any +way. + +Example, convert all JSON objects into the integer 5: + + my $js = JSON::PP->new->filter_json_object(sub { 5 }); + # returns [5] + $js->decode('[{}]'); + # returns 5 + $js->decode('{"a":1, "b":2}'); + +=head2 filter_json_single_key_object + + $json = $json->filter_json_single_key_object($key [=> $coderef]) + +Works remotely similar to C<filter_json_object>, but is only called for +JSON objects having a single key named C<$key>. + +This C<$coderef> is called before the one specified via +C<filter_json_object>, if any. It gets passed the single value in the JSON +object. If it returns a single value, it will be inserted into the data +structure. If it returns nothing (not even C<undef> but the empty list), +the callback from C<filter_json_object> will be called next, as if no +single-key callback were specified. + +If C<$coderef> is omitted or undefined, the corresponding callback will be +disabled. There can only ever be one callback for a given key. + +As this callback gets called less often then the C<filter_json_object> +one, decoding speed will not usually suffer as much. Therefore, single-key +objects make excellent targets to serialise Perl objects into, especially +as single-key JSON objects are as close to the type-tagged value concept +as JSON gets (it's basically an ID/VALUE tuple). Of course, JSON does not +support this in any way, so you need to make sure your data never looks +like a serialised Perl hash. + +Typical names for the single object key are C<__class_whatever__>, or +C<$__dollars_are_rarely_used__$> or C<}ugly_brace_placement>, or even +things like C<__class_md5sum(classname)__>, to reduce the risk of clashing +with real hashes. + +Example, decode JSON objects of the form C<< { "__widget__" => <id> } >> +into the corresponding C<< $WIDGET{<id>} >> object: + + # return whatever is in $WIDGET{5}: + JSON::PP + ->new + ->filter_json_single_key_object (__widget__ => sub { + $WIDGET{ $_[0] } + }) + ->decode ('{"__widget__": 5') + + # this can be used with a TO_JSON method in some "widget" class + # for serialisation to json: + sub WidgetBase::TO_JSON { + my ($self) = @_; + + unless ($self->{id}) { + $self->{id} = ..get..some..id..; + $WIDGET{$self->{id}} = $self; + } + + { __widget__ => $self->{id} } + } + +=head2 shrink + + $json = $json->shrink([$enable]) + + $enabled = $json->get_shrink + +If C<$enable> is true (or missing), the string returned by C<encode> will +be shrunk (i.e. downgraded if possible). + +The actual definition of what shrink does might change in future versions, +but it will always try to save space at the expense of time. + +If C<$enable> is false, then JSON::PP does nothing. + +=head2 max_depth + + $json = $json->max_depth([$maximum_nesting_depth]) + + $max_depth = $json->get_max_depth + +Sets the maximum nesting level (default C<512>) accepted while encoding +or decoding. If a higher nesting level is detected in JSON text or a Perl +data structure, then the encoder and decoder will stop and croak at that +point. + +Nesting level is defined by number of hash- or arrayrefs that the encoder +needs to traverse to reach a given point or the number of C<{> or C<[> +characters without their matching closing parenthesis crossed to reach a +given character in a string. + +Setting the maximum depth to one disallows any nesting, so that ensures +that the object is only a single hash/object or array. + +If no argument is given, the highest possible setting will be used, which +is rarely useful. + +See L<JSON::XS/SECURITY CONSIDERATIONS> for more info on why this is useful. + +=head2 max_size + + $json = $json->max_size([$maximum_string_size]) + + $max_size = $json->get_max_size + +Set the maximum length a JSON text may have (in bytes) where decoding is +being attempted. The default is C<0>, meaning no limit. When C<decode> +is called on a string that is longer then this many bytes, it will not +attempt to decode the string but throw an exception. This setting has no +effect on C<encode> (yet). + +If no argument is given, the limit check will be deactivated (same as when +C<0> is specified). + +See L<JSON::XS/SECURITY CONSIDERATIONS> for more info on why this is useful. + +=head2 encode + + $json_text = $json->encode($perl_scalar) + +Converts the given Perl value or data structure to its JSON +representation. Croaks on error. + +=head2 decode + + $perl_scalar = $json->decode($json_text) + +The opposite of C<encode>: expects a JSON text and tries to parse it, +returning the resulting simple scalar or reference. Croaks on error. + +=head2 decode_prefix + + ($perl_scalar, $characters) = $json->decode_prefix($json_text) + +This works like the C<decode> method, but instead of raising an exception +when there is trailing garbage after the first JSON object, it will +silently stop parsing there and return the number of characters consumed +so far. + +This is useful if your JSON texts are not delimited by an outer protocol +and you need to know where the JSON text ends. + + JSON::PP->new->decode_prefix ("[1] the tail") + => ([1], 3) + +=head1 FLAGS FOR JSON::PP ONLY + +The following flags and properties are for JSON::PP only. If you use +any of these, you can't make your application run faster by replacing +JSON::PP with JSON::XS. If you need these and also speed boost, +you might want to try L<Cpanel::JSON::XS>, a fork of JSON::XS by +Reini Urban, which supports some of these (with a different set of +incompatibilities). Most of these historical flags are only kept +for backward compatibility, and should not be used in a new application. + +=head2 allow_singlequote + + $json = $json->allow_singlequote([$enable]) + $enabled = $json->get_allow_singlequote + +If C<$enable> is true (or missing), then C<decode> will accept +invalid JSON texts that contain strings that begin and end with +single quotation marks. C<encode> will not be affected in any way. +I<Be aware that this option makes you accept invalid JSON texts +as if they were valid!>. I suggest only to use this option to +parse application-specific files written by humans (configuration +files, resource files etc.) + +If C<$enable> is false (the default), then C<decode> will only accept +valid JSON texts. + + $json->allow_singlequote->decode(qq|{"foo":'bar'}|); + $json->allow_singlequote->decode(qq|{'foo':"bar"}|); + $json->allow_singlequote->decode(qq|{'foo':'bar'}|); + +=head2 allow_barekey + + $json = $json->allow_barekey([$enable]) + $enabled = $json->get_allow_barekey + +If C<$enable> is true (or missing), then C<decode> will accept +invalid JSON texts that contain JSON objects whose names don't +begin and end with quotation marks. C<encode> will not be affected +in any way. I<Be aware that this option makes you accept invalid JSON +texts as if they were valid!>. I suggest only to use this option to +parse application-specific files written by humans (configuration +files, resource files etc.) + +If C<$enable> is false (the default), then C<decode> will only accept +valid JSON texts. + + $json->allow_barekey->decode(qq|{foo:"bar"}|); + +=head2 allow_bignum + + $json = $json->allow_bignum([$enable]) + $enabled = $json->get_allow_bignum + +If C<$enable> is true (or missing), then C<decode> will convert +big integers Perl cannot handle as integer into L<Math::BigInt> +objects and convert floating numbers into L<Math::BigFloat> +objects. C<encode> will convert C<Math::BigInt> and C<Math::BigFloat> +objects into JSON numbers. + + $json->allow_nonref->allow_bignum; + $bigfloat = $json->decode('2.000000000000000000000000001'); + print $json->encode($bigfloat); + # => 2.000000000000000000000000001 + +See also L<MAPPING>. + +=head2 loose + + $json = $json->loose([$enable]) + $enabled = $json->get_loose + +If C<$enable> is true (or missing), then C<decode> will accept +invalid JSON texts that contain unescaped [\x00-\x1f\x22\x5c] +characters. C<encode> will not be affected in any way. +I<Be aware that this option makes you accept invalid JSON texts +as if they were valid!>. I suggest only to use this option to +parse application-specific files written by humans (configuration +files, resource files etc.) + +If C<$enable> is false (the default), then C<decode> will only accept +valid JSON texts. + + $json->loose->decode(qq|["abc + def"]|); + +=head2 escape_slash + + $json = $json->escape_slash([$enable]) + $enabled = $json->get_escape_slash + +If C<$enable> is true (or missing), then C<encode> will explicitly +escape I<slash> (solidus; C<U+002F>) characters to reduce the risk of +XSS (cross site scripting) that may be caused by C<< </script> >> +in a JSON text, with the cost of bloating the size of JSON texts. + +This option may be useful when you embed JSON in HTML, but embedding +arbitrary JSON in HTML (by some HTML template toolkit or by string +interpolation) is risky in general. You must escape necessary +characters in correct order, depending on the context. + +C<decode> will not be affected in any way. + +=head2 indent_length + + $json = $json->indent_length($number_of_spaces) + $length = $json->get_indent_length + +This option is only useful when you also enable C<indent> or C<pretty>. + +JSON::XS indents with three spaces when you C<encode> (if requested +by C<indent> or C<pretty>), and the number cannot be changed. +JSON::PP allows you to change/get the number of indent spaces with these +mutator/accessor. The default number of spaces is three (the same as +JSON::XS), and the acceptable range is from C<0> (no indentation; +it'd be better to disable indentation by C<indent(0)>) to C<15>. + +=head2 sort_by + + $json = $json->sort_by($code_ref) + $json = $json->sort_by($subroutine_name) + +If you just want to sort keys (names) in JSON objects when you +C<encode>, enable C<canonical> option (see above) that allows you to +sort object keys alphabetically. + +If you do need to sort non-alphabetically for whatever reasons, +you can give a code reference (or a subroutine name) to C<sort_by>, +then the argument will be passed to Perl's C<sort> built-in function. + +As the sorting is done in the JSON::PP scope, you usually need to +prepend C<JSON::PP::> to the subroutine name, and the special variables +C<$a> and C<$b> used in the subrontine used by C<sort> function. + +Example: + + my %ORDER = (id => 1, class => 2, name => 3); + $json->sort_by(sub { + ($ORDER{$JSON::PP::a} // 999) <=> ($ORDER{$JSON::PP::b} // 999) + or $JSON::PP::a cmp $JSON::PP::b + }); + print $json->encode([ + {name => 'CPAN', id => 1, href => 'http://cpan.org'} + ]); + # [{"id":1,"name":"CPAN","href":"http://cpan.org"}] + +Note that C<sort_by> affects all the plain hashes in the data structure. +If you need finer control, C<tie> necessary hashes with a module that +implements ordered hash (such as L<Hash::Ordered> and L<Tie::IxHash>). +C<canonical> and C<sort_by> don't affect the key order in C<tie>d +hashes. + + use Hash::Ordered; + tie my %hash, 'Hash::Ordered', + (name => 'CPAN', id => 1, href => 'http://cpan.org'); + print $json->encode([\%hash]); + # [{"name":"CPAN","id":1,"href":"http://cpan.org"}] # order is kept + +=head1 INCREMENTAL PARSING + +This section is also taken from JSON::XS. + +In some cases, there is the need for incremental parsing of JSON +texts. While this module always has to keep both JSON text and resulting +Perl data structure in memory at one time, it does allow you to parse a +JSON stream incrementally. It does so by accumulating text until it has +a full JSON object, which it then can decode. This process is similar to +using C<decode_prefix> to see if a full JSON object is available, but +is much more efficient (and can be implemented with a minimum of method +calls). + +JSON::PP will only attempt to parse the JSON text once it is sure it +has enough text to get a decisive result, using a very simple but +truly incremental parser. This means that it sometimes won't stop as +early as the full parser, for example, it doesn't detect mismatched +parentheses. The only thing it guarantees is that it starts decoding as +soon as a syntactically valid JSON text has been seen. This means you need +to set resource limits (e.g. C<max_size>) to ensure the parser will stop +parsing in the presence if syntax errors. + +The following methods implement this incremental parser. + +=head2 incr_parse + + $json->incr_parse( [$string] ) # void context + + $obj_or_undef = $json->incr_parse( [$string] ) # scalar context + + @obj_or_empty = $json->incr_parse( [$string] ) # list context + +This is the central parsing function. It can both append new text and +extract objects from the stream accumulated so far (both of these +functions are optional). + +If C<$string> is given, then this string is appended to the already +existing JSON fragment stored in the C<$json> object. + +After that, if the function is called in void context, it will simply +return without doing anything further. This can be used to add more text +in as many chunks as you want. + +If the method is called in scalar context, then it will try to extract +exactly I<one> JSON object. If that is successful, it will return this +object, otherwise it will return C<undef>. If there is a parse error, +this method will croak just as C<decode> would do (one can then use +C<incr_skip> to skip the erroneous part). This is the most common way of +using the method. + +And finally, in list context, it will try to extract as many objects +from the stream as it can find and return them, or the empty list +otherwise. For this to work, there must be no separators (other than +whitespace) between the JSON objects or arrays, instead they must be +concatenated back-to-back. If an error occurs, an exception will be +raised as in the scalar context case. Note that in this case, any +previously-parsed JSON texts will be lost. + +Example: Parse some JSON arrays/objects in a given string and return +them. + + my @objs = JSON::PP->new->incr_parse ("[5][7][1,2]"); + +=head2 incr_text + + $lvalue_string = $json->incr_text + +This method returns the currently stored JSON fragment as an lvalue, that +is, you can manipulate it. This I<only> works when a preceding call to +C<incr_parse> in I<scalar context> successfully returned an object. Under +all other circumstances you must not call this function (I mean it. +although in simple tests it might actually work, it I<will> fail under +real world conditions). As a special exception, you can also call this +method before having parsed anything. + +That means you can only use this function to look at or manipulate text +before or after complete JSON objects, not while the parser is in the +middle of parsing a JSON object. + +This function is useful in two cases: a) finding the trailing text after a +JSON object or b) parsing multiple JSON objects separated by non-JSON text +(such as commas). + +=head2 incr_skip + + $json->incr_skip + +This will reset the state of the incremental parser and will remove +the parsed text from the input buffer so far. This is useful after +C<incr_parse> died, in which case the input buffer and incremental parser +state is left unchanged, to skip the text parsed so far and to reset the +parse state. + +The difference to C<incr_reset> is that only text until the parse error +occurred is removed. + +=head2 incr_reset + + $json->incr_reset + +This completely resets the incremental parser, that is, after this call, +it will be as if the parser had never parsed anything. + +This is useful if you want to repeatedly parse JSON objects and want to +ignore any trailing data, which means you have to reset the parser after +each successful decode. + +=head1 MAPPING + +Most of this section is also taken from JSON::XS. + +This section describes how JSON::PP maps Perl values to JSON values and +vice versa. These mappings are designed to "do the right thing" in most +circumstances automatically, preserving round-tripping characteristics +(what you put in comes out as something equivalent). + +For the more enlightened: note that in the following descriptions, +lowercase I<perl> refers to the Perl interpreter, while uppercase I<Perl> +refers to the abstract Perl language itself. + +=head2 JSON -> PERL + +=over 4 + +=item object + +A JSON object becomes a reference to a hash in Perl. No ordering of object +keys is preserved (JSON does not preserve object key ordering itself). + +=item array + +A JSON array becomes a reference to an array in Perl. + +=item string + +A JSON string becomes a string scalar in Perl - Unicode codepoints in JSON +are represented by the same codepoints in the Perl string, so no manual +decoding is necessary. + +=item number + +A JSON number becomes either an integer, numeric (floating point) or +string scalar in perl, depending on its range and any fractional parts. On +the Perl level, there is no difference between those as Perl handles all +the conversion details, but an integer may take slightly less memory and +might represent more values exactly than floating point numbers. + +If the number consists of digits only, JSON::PP will try to represent +it as an integer value. If that fails, it will try to represent it as +a numeric (floating point) value if that is possible without loss of +precision. Otherwise it will preserve the number as a string value (in +which case you lose roundtripping ability, as the JSON number will be +re-encoded to a JSON string). + +Numbers containing a fractional or exponential part will always be +represented as numeric (floating point) values, possibly at a loss of +precision (in which case you might lose perfect roundtripping ability, but +the JSON number will still be re-encoded as a JSON number). + +Note that precision is not accuracy - binary floating point values cannot +represent most decimal fractions exactly, and when converting from and to +floating point, JSON::PP only guarantees precision up to but not including +the least significant bit. + +When C<allow_bignum> is enabled, big integer values and any numeric +values will be converted into L<Math::BigInt> and L<Math::BigFloat> +objects respectively, without becoming string scalars or losing +precision. + +=item true, false + +These JSON atoms become C<JSON::PP::true> and C<JSON::PP::false>, +respectively. They are overloaded to act almost exactly like the numbers +C<1> and C<0>. You can check whether a scalar is a JSON boolean by using +the C<JSON::PP::is_bool> function. + +=item null + +A JSON null atom becomes C<undef> in Perl. + +=item shell-style comments (C<< # I<text> >>) + +As a nonstandard extension to the JSON syntax that is enabled by the +C<relaxed> setting, shell-style comments are allowed. They can start +anywhere outside strings and go till the end of the line. + +=item tagged values (C<< (I<tag>)I<value> >>). + +Another nonstandard extension to the JSON syntax, enabled with the +C<allow_tags> setting, are tagged values. In this implementation, the +I<tag> must be a perl package/class name encoded as a JSON string, and the +I<value> must be a JSON array encoding optional constructor arguments. + +See L<OBJECT SERIALISATION>, below, for details. + +=back + + +=head2 PERL -> JSON + +The mapping from Perl to JSON is slightly more difficult, as Perl is a +truly typeless language, so we can only guess which JSON type is meant by +a Perl value. + +=over 4 + +=item hash references + +Perl hash references become JSON objects. As there is no inherent +ordering in hash keys (or JSON objects), they will usually be encoded +in a pseudo-random order. JSON::PP can optionally sort the hash keys +(determined by the I<canonical> flag and/or I<sort_by> property), so +the same data structure will serialise to the same JSON text (given +same settings and version of JSON::PP), but this incurs a runtime +overhead and is only rarely useful, e.g. when you want to compare some +JSON text against another for equality. + +=item array references + +Perl array references become JSON arrays. + +=item other references + +Other unblessed references are generally not allowed and will cause an +exception to be thrown, except for references to the integers C<0> and +C<1>, which get turned into C<false> and C<true> atoms in JSON. You can +also use C<JSON::PP::false> and C<JSON::PP::true> to improve +readability. + + to_json [\0, JSON::PP::true] # yields [false,true] + +=item JSON::PP::true, JSON::PP::false + +These special values become JSON true and JSON false values, +respectively. You can also use C<\1> and C<\0> directly if you want. + +=item JSON::PP::null + +This special value becomes JSON null. + +=item blessed objects + +Blessed objects are not directly representable in JSON, but C<JSON::PP> +allows various ways of handling objects. See L<OBJECT SERIALISATION>, +below, for details. + +=item simple scalars + +Simple Perl scalars (any scalar that is not a reference) are the most +difficult objects to encode: JSON::PP will encode undefined scalars as +JSON C<null> values, scalars that have last been used in a string context +before encoding as JSON strings, and anything else as number value: + + # dump as number + encode_json [2] # yields [2] + encode_json [-3.0e17] # yields [-3e+17] + my $value = 5; encode_json [$value] # yields [5] + + # used as string, so dump as string + print $value; + encode_json [$value] # yields ["5"] + + # undef becomes null + encode_json [undef] # yields [null] + +You can force the type to be a JSON string by stringifying it: + + my $x = 3.1; # some variable containing a number + "$x"; # stringified + $x .= ""; # another, more awkward way to stringify + print $x; # perl does it for you, too, quite often + # (but for older perls) + +You can force the type to be a JSON number by numifying it: + + my $x = "3"; # some variable containing a string + $x += 0; # numify it, ensuring it will be dumped as a number + $x *= 1; # same thing, the choice is yours. + +You can not currently force the type in other, less obscure, ways. + +Since version 2.91_01, JSON::PP uses a different number detection logic +that converts a scalar that is possible to turn into a number safely. +The new logic is slightly faster, and tends to help people who use older +perl or who want to encode complicated data structure. However, this may +results in a different JSON text from the one JSON::XS encodes (and +thus may break tests that compare entire JSON texts). If you do +need the previous behavior for compatibility or for finer control, +set PERL_JSON_PP_USE_B environmental variable to true before you +C<use> JSON::PP (or JSON.pm). + +Note that numerical precision has the same meaning as under Perl (so +binary to decimal conversion follows the same rules as in Perl, which +can differ to other languages). Also, your perl interpreter might expose +extensions to the floating point numbers of your platform, such as +infinities or NaN's - these cannot be represented in JSON, and it is an +error to pass those in. + +JSON::PP (and JSON::XS) trusts what you pass to C<encode> method +(or C<encode_json> function) is a clean, validated data structure with +values that can be represented as valid JSON values only, because it's +not from an external data source (as opposed to JSON texts you pass to +C<decode> or C<decode_json>, which JSON::PP considers tainted and +doesn't trust). As JSON::PP doesn't know exactly what you and consumers +of your JSON texts want the unexpected values to be (you may want to +convert them into null, or to stringify them with or without +normalisation (string representation of infinities/NaN may vary +depending on platforms), or to croak without conversion), you're advised +to do what you and your consumers need before you encode, and also not +to numify values that may start with values that look like a number +(including infinities/NaN), without validating. + +=back + +=head2 OBJECT SERIALISATION + +As JSON cannot directly represent Perl objects, you have to choose between +a pure JSON representation (without the ability to deserialise the object +automatically again), and a nonstandard extension to the JSON syntax, +tagged values. + +=head3 SERIALISATION + +What happens when C<JSON::PP> encounters a Perl object depends on the +C<allow_blessed>, C<convert_blessed>, C<allow_tags> and C<allow_bignum> +settings, which are used in this order: + +=over 4 + +=item 1. C<allow_tags> is enabled and the object has a C<FREEZE> method. + +In this case, C<JSON::PP> creates a tagged JSON value, using a nonstandard +extension to the JSON syntax. + +This works by invoking the C<FREEZE> method on the object, with the first +argument being the object to serialise, and the second argument being the +constant string C<JSON> to distinguish it from other serialisers. + +The C<FREEZE> method can return any number of values (i.e. zero or +more). These values and the paclkage/classname of the object will then be +encoded as a tagged JSON value in the following format: + + ("classname")[FREEZE return values...] + +e.g.: + + ("URI")["http://www.google.com/"] + ("MyDate")[2013,10,29] + ("ImageData::JPEG")["Z3...VlCg=="] + +For example, the hypothetical C<My::Object> C<FREEZE> method might use the +objects C<type> and C<id> members to encode the object: + + sub My::Object::FREEZE { + my ($self, $serialiser) = @_; + + ($self->{type}, $self->{id}) + } + +=item 2. C<convert_blessed> is enabled and the object has a C<TO_JSON> method. + +In this case, the C<TO_JSON> method of the object is invoked in scalar +context. It must return a single scalar that can be directly encoded into +JSON. This scalar replaces the object in the JSON text. + +For example, the following C<TO_JSON> method will convert all L<URI> +objects to JSON strings when serialised. The fact that these values +originally were L<URI> objects is lost. + + sub URI::TO_JSON { + my ($uri) = @_; + $uri->as_string + } + +=item 3. C<allow_bignum> is enabled and the object is a C<Math::BigInt> or C<Math::BigFloat>. + +The object will be serialised as a JSON number value. + +=item 4. C<allow_blessed> is enabled. + +The object will be serialised as a JSON null value. + +=item 5. none of the above + +If none of the settings are enabled or the respective methods are missing, +C<JSON::PP> throws an exception. + +=back + +=head3 DESERIALISATION + +For deserialisation there are only two cases to consider: either +nonstandard tagging was used, in which case C<allow_tags> decides, +or objects cannot be automatically be deserialised, in which +case you can use postprocessing or the C<filter_json_object> or +C<filter_json_single_key_object> callbacks to get some real objects our of +your JSON. + +This section only considers the tagged value case: a tagged JSON object +is encountered during decoding and C<allow_tags> is disabled, a parse +error will result (as if tagged values were not part of the grammar). + +If C<allow_tags> is enabled, C<JSON::PP> will look up the C<THAW> method +of the package/classname used during serialisation (it will not attempt +to load the package as a Perl module). If there is no such method, the +decoding will fail with an error. + +Otherwise, the C<THAW> method is invoked with the classname as first +argument, the constant string C<JSON> as second argument, and all the +values from the JSON array (the values originally returned by the +C<FREEZE> method) as remaining arguments. + +The method must then return the object. While technically you can return +any Perl scalar, you might have to enable the C<allow_nonref> setting to +make that work in all cases, so better return an actual blessed reference. + +As an example, let's implement a C<THAW> function that regenerates the +C<My::Object> from the C<FREEZE> example earlier: + + sub My::Object::THAW { + my ($class, $serialiser, $type, $id) = @_; + + $class->new (type => $type, id => $id) + } + + +=head1 ENCODING/CODESET FLAG NOTES + +This section is taken from JSON::XS. + +The interested reader might have seen a number of flags that signify +encodings or codesets - C<utf8>, C<latin1> and C<ascii>. There seems to be +some confusion on what these do, so here is a short comparison: + +C<utf8> controls whether the JSON text created by C<encode> (and expected +by C<decode>) is UTF-8 encoded or not, while C<latin1> and C<ascii> only +control whether C<encode> escapes character values outside their respective +codeset range. Neither of these flags conflict with each other, although +some combinations make less sense than others. + +Care has been taken to make all flags symmetrical with respect to +C<encode> and C<decode>, that is, texts encoded with any combination of +these flag values will be correctly decoded when the same flags are used +- in general, if you use different flag settings while encoding vs. when +decoding you likely have a bug somewhere. + +Below comes a verbose discussion of these flags. Note that a "codeset" is +simply an abstract set of character-codepoint pairs, while an encoding +takes those codepoint numbers and I<encodes> them, in our case into +octets. Unicode is (among other things) a codeset, UTF-8 is an encoding, +and ISO-8859-1 (= latin 1) and ASCII are both codesets I<and> encodings at +the same time, which can be confusing. + +=over 4 + +=item C<utf8> flag disabled + +When C<utf8> is disabled (the default), then C<encode>/C<decode> generate +and expect Unicode strings, that is, characters with high ordinal Unicode +values (> 255) will be encoded as such characters, and likewise such +characters are decoded as-is, no changes to them will be done, except +"(re-)interpreting" them as Unicode codepoints or Unicode characters, +respectively (to Perl, these are the same thing in strings unless you do +funny/weird/dumb stuff). + +This is useful when you want to do the encoding yourself (e.g. when you +want to have UTF-16 encoded JSON texts) or when some other layer does +the encoding for you (for example, when printing to a terminal using a +filehandle that transparently encodes to UTF-8 you certainly do NOT want +to UTF-8 encode your data first and have Perl encode it another time). + +=item C<utf8> flag enabled + +If the C<utf8>-flag is enabled, C<encode>/C<decode> will encode all +characters using the corresponding UTF-8 multi-byte sequence, and will +expect your input strings to be encoded as UTF-8, that is, no "character" +of the input string must have any value > 255, as UTF-8 does not allow +that. + +The C<utf8> flag therefore switches between two modes: disabled means you +will get a Unicode string in Perl, enabled means you get an UTF-8 encoded +octet/binary string in Perl. + +=item C<latin1> or C<ascii> flags enabled + +With C<latin1> (or C<ascii>) enabled, C<encode> will escape characters +with ordinal values > 255 (> 127 with C<ascii>) and encode the remaining +characters as specified by the C<utf8> flag. + +If C<utf8> is disabled, then the result is also correctly encoded in those +character sets (as both are proper subsets of Unicode, meaning that a +Unicode string with all character values < 256 is the same thing as a +ISO-8859-1 string, and a Unicode string with all character values < 128 is +the same thing as an ASCII string in Perl). + +If C<utf8> is enabled, you still get a correct UTF-8-encoded string, +regardless of these flags, just some more characters will be escaped using +C<\uXXXX> then before. + +Note that ISO-8859-1-I<encoded> strings are not compatible with UTF-8 +encoding, while ASCII-encoded strings are. That is because the ISO-8859-1 +encoding is NOT a subset of UTF-8 (despite the ISO-8859-1 I<codeset> being +a subset of Unicode), while ASCII is. + +Surprisingly, C<decode> will ignore these flags and so treat all input +values as governed by the C<utf8> flag. If it is disabled, this allows you +to decode ISO-8859-1- and ASCII-encoded strings, as both strict subsets of +Unicode. If it is enabled, you can correctly decode UTF-8 encoded strings. + +So neither C<latin1> nor C<ascii> are incompatible with the C<utf8> flag - +they only govern when the JSON output engine escapes a character or not. + +The main use for C<latin1> is to relatively efficiently store binary data +as JSON, at the expense of breaking compatibility with most JSON decoders. + +The main use for C<ascii> is to force the output to not contain characters +with values > 127, which means you can interpret the resulting string +as UTF-8, ISO-8859-1, ASCII, KOI8-R or most about any character set and +8-bit-encoding, and still get the same data structure back. This is useful +when your channel for JSON transfer is not 8-bit clean or the encoding +might be mangled in between (e.g. in mail), and works because ASCII is a +proper subset of most 8-bit and multibyte encodings in use in the world. + +=back + +=head1 BUGS + +Please report bugs on a specific behavior of this module to RT or GitHub +issues (preferred): + +L<https://github.com/makamaka/JSON-PP/issues> + +L<https://rt.cpan.org/Public/Dist/Display.html?Queue=JSON-PP> + +As for new features and requests to change common behaviors, please +ask the author of JSON::XS (Marc Lehmann, E<lt>schmorp[at]schmorp.deE<gt>) +first, by email (important!), to keep compatibility among JSON.pm backends. + +Generally speaking, if you need something special for you, you are advised +to create a new module, maybe based on L<JSON::Tiny>, which is smaller and +written in a much cleaner way than this module. + +=head1 SEE ALSO + +The F<json_pp> command line utility for quick experiments. + +L<JSON::XS>, L<Cpanel::JSON::XS>, and L<JSON::Tiny> for faster alternatives. +L<JSON> and L<JSON::MaybeXS> for easy migration. + +L<JSON::backportPP::Compat5005> and L<JSON::backportPP::Compat5006> for older perl users. + +RFC4627 (L<http://www.ietf.org/rfc/rfc4627.txt>) + +RFC7159 (L<http://www.ietf.org/rfc/rfc7159.txt>) + +RFC8259 (L<http://www.ietf.org/rfc/rfc8259.txt>) + +=head1 AUTHOR + +Makamaka Hannyaharamitu, E<lt>makamaka[at]cpan.orgE<gt> + +=head1 CURRENT MAINTAINER + +Kenichi Ishigaki, E<lt>ishigaki[at]cpan.orgE<gt> + +=head1 COPYRIGHT AND LICENSE + +Copyright 2007-2016 by Makamaka Hannyaharamitu + +Most of the documentation is taken from JSON::XS by Marc Lehmann + +This library is free software; you can redistribute it and/or modify +it under the same terms as Perl itself. + +=cut diff --git a/lib/JSON/backportPP/Boolean.pm b/lib/JSON/backportPP/Boolean.pm new file mode 100644 index 0000000..6bb7b8c --- /dev/null +++ b/lib/JSON/backportPP/Boolean.pm @@ -0,0 +1,43 @@ +package # This is JSON::backportPP + JSON::PP::Boolean; + +use strict; +require overload; +local $^W; +overload::import('overload', + "0+" => sub { ${$_[0]} }, + "++" => sub { $_[0] = ${$_[0]} + 1 }, + "--" => sub { $_[0] = ${$_[0]} - 1 }, + fallback => 1, +); + +$JSON::backportPP::Boolean::VERSION = '4.02'; + +1; + +__END__ + +=head1 NAME + +JSON::PP::Boolean - dummy module providing JSON::PP::Boolean + +=head1 SYNOPSIS + + # do not "use" yourself + +=head1 DESCRIPTION + +This module exists only to provide overload resolution for Storable and similar modules. See +L<JSON::PP> for more info about this class. + +=head1 AUTHOR + +This idea is from L<JSON::XS::Boolean> written by Marc Lehmann <schmorp[at]schmorp.de> + +=head1 LICENSE + +This library is free software; you can redistribute it and/or modify +it under the same terms as Perl itself. + +=cut + diff --git a/lib/JSON/backportPP/Compat5005.pm b/lib/JSON/backportPP/Compat5005.pm new file mode 100644 index 0000000..139990e --- /dev/null +++ b/lib/JSON/backportPP/Compat5005.pm @@ -0,0 +1,131 @@ +package # This is JSON::backportPP + JSON::backportPP5005; + +use 5.005; +use strict; + +my @properties; + +$JSON::PP5005::VERSION = '1.10'; + +BEGIN { + + sub utf8::is_utf8 { + 0; # It is considered that UTF8 flag off for Perl 5.005. + } + + sub utf8::upgrade { + } + + sub utf8::downgrade { + 1; # must always return true. + } + + sub utf8::encode { + } + + sub utf8::decode { + } + + *JSON::PP::JSON_PP_encode_ascii = \&_encode_ascii; + *JSON::PP::JSON_PP_encode_latin1 = \&_encode_latin1; + *JSON::PP::JSON_PP_decode_surrogates = \&_decode_surrogates; + *JSON::PP::JSON_PP_decode_unicode = \&_decode_unicode; + + # missing in B module. + sub B::SVp_IOK () { 0x01000000; } + sub B::SVp_NOK () { 0x02000000; } + sub B::SVp_POK () { 0x04000000; } + + $INC{'bytes.pm'} = 1; # dummy +} + + + +sub _encode_ascii { + join('', map { $_ <= 127 ? chr($_) : sprintf('\u%04x', $_) } unpack('C*', $_[0]) ); +} + + +sub _encode_latin1 { + join('', map { chr($_) } unpack('C*', $_[0]) ); +} + + +sub _decode_surrogates { # from http://homepage1.nifty.com/nomenclator/unicode/ucs_utf.htm + my $uni = 0x10000 + (hex($_[0]) - 0xD800) * 0x400 + (hex($_[1]) - 0xDC00); # from perlunicode + my $bit = unpack('B32', pack('N', $uni)); + + if ( $bit =~ /^00000000000(...)(......)(......)(......)$/ ) { + my ($w, $x, $y, $z) = ($1, $2, $3, $4); + return pack('B*', sprintf('11110%s10%s10%s10%s', $w, $x, $y, $z)); + } + else { + Carp::croak("Invalid surrogate pair"); + } +} + + +sub _decode_unicode { + my ($u) = @_; + my ($utf8bit); + + if ( $u =~ /^00([89a-f][0-9a-f])$/i ) { # 0x80-0xff + return pack( 'H2', $1 ); + } + + my $bit = unpack("B*", pack("H*", $u)); + + if ( $bit =~ /^00000(.....)(......)$/ ) { + $utf8bit = sprintf('110%s10%s', $1, $2); + } + elsif ( $bit =~ /^(....)(......)(......)$/ ) { + $utf8bit = sprintf('1110%s10%s10%s', $1, $2, $3); + } + else { + Carp::croak("Invalid escaped unicode"); + } + + return pack('B*', $utf8bit); +} + + +sub JSON::PP::incr_text { + $_[0]->{_incr_parser} ||= JSON::PP::IncrParser->new; + + if ( $_[0]->{_incr_parser}->{incr_parsing} ) { + Carp::croak("incr_text can not be called when the incremental parser already started parsing"); + } + + $_[0]->{_incr_parser}->{incr_text} = $_[1] if ( @_ > 1 ); + $_[0]->{_incr_parser}->{incr_text}; +} + + +1; +__END__ + +=pod + +=head1 NAME + +JSON::PP5005 - Helper module in using JSON::PP in Perl 5.005 + +=head1 DESCRIPTION + +JSON::PP calls internally. + +=head1 AUTHOR + +Makamaka Hannyaharamitu, E<lt>makamaka[at]cpan.orgE<gt> + + +=head1 COPYRIGHT AND LICENSE + +Copyright 2007-2012 by Makamaka Hannyaharamitu + +This library is free software; you can redistribute it and/or modify +it under the same terms as Perl itself. + +=cut + diff --git a/lib/JSON/backportPP/Compat5006.pm b/lib/JSON/backportPP/Compat5006.pm new file mode 100644 index 0000000..7736fd8 --- /dev/null +++ b/lib/JSON/backportPP/Compat5006.pm @@ -0,0 +1,173 @@ +package # This is JSON::backportPP + JSON::backportPP56; + +use 5.006; +use strict; + +my @properties; + +$JSON::PP56::VERSION = '1.08'; + +BEGIN { + + sub utf8::is_utf8 { + my $len = length $_[0]; # char length + { + use bytes; # byte length; + return $len != length $_[0]; # if !=, UTF8-flagged on. + } + } + + + sub utf8::upgrade { + ; # noop; + } + + + sub utf8::downgrade ($;$) { + return 1 unless ( utf8::is_utf8( $_[0] ) ); + + if ( _is_valid_utf8( $_[0] ) ) { + my $downgrade; + for my $c ( unpack( "U*", $_[0] ) ) { + if ( $c < 256 ) { + $downgrade .= pack("C", $c); + } + else { + $downgrade .= pack("U", $c); + } + } + $_[0] = $downgrade; + return 1; + } + else { + Carp::croak("Wide character in subroutine entry") unless ( $_[1] ); + 0; + } + } + + + sub utf8::encode ($) { # UTF8 flag off + if ( utf8::is_utf8( $_[0] ) ) { + $_[0] = pack( "C*", unpack( "C*", $_[0] ) ); + } + else { + $_[0] = pack( "U*", unpack( "C*", $_[0] ) ); + $_[0] = pack( "C*", unpack( "C*", $_[0] ) ); + } + } + + + sub utf8::decode ($) { # UTF8 flag on + if ( _is_valid_utf8( $_[0] ) ) { + utf8::downgrade( $_[0] ); + $_[0] = pack( "U*", unpack( "U*", $_[0] ) ); + } + } + + + *JSON::PP::JSON_PP_encode_ascii = \&_encode_ascii; + *JSON::PP::JSON_PP_encode_latin1 = \&_encode_latin1; + *JSON::PP::JSON_PP_decode_surrogates = \&JSON::PP::_decode_surrogates; + *JSON::PP::JSON_PP_decode_unicode = \&JSON::PP::_decode_unicode; + + unless ( defined &B::SVp_NOK ) { # missing in B module. + eval q{ sub B::SVp_NOK () { 0x02000000; } }; + } + +} + + + +sub _encode_ascii { + join('', + map { + $_ <= 127 ? + chr($_) : + $_ <= 65535 ? + sprintf('\u%04x', $_) : sprintf('\u%x\u%x', JSON::PP::_encode_surrogates($_)); + } _unpack_emu($_[0]) + ); +} + + +sub _encode_latin1 { + join('', + map { + $_ <= 255 ? + chr($_) : + $_ <= 65535 ? + sprintf('\u%04x', $_) : sprintf('\u%x\u%x', JSON::PP::_encode_surrogates($_)); + } _unpack_emu($_[0]) + ); +} + + +sub _unpack_emu { # for Perl 5.6 unpack warnings + return !utf8::is_utf8($_[0]) ? unpack('C*', $_[0]) + : _is_valid_utf8($_[0]) ? unpack('U*', $_[0]) + : unpack('C*', $_[0]); +} + + +sub _is_valid_utf8 { + my $str = $_[0]; + my $is_utf8; + + while ($str =~ /(?: + ( + [\x00-\x7F] + |[\xC2-\xDF][\x80-\xBF] + |[\xE0][\xA0-\xBF][\x80-\xBF] + |[\xE1-\xEC][\x80-\xBF][\x80-\xBF] + |[\xED][\x80-\x9F][\x80-\xBF] + |[\xEE-\xEF][\x80-\xBF][\x80-\xBF] + |[\xF0][\x90-\xBF][\x80-\xBF][\x80-\xBF] + |[\xF1-\xF3][\x80-\xBF][\x80-\xBF][\x80-\xBF] + |[\xF4][\x80-\x8F][\x80-\xBF][\x80-\xBF] + ) + | (.) + )/xg) + { + if (defined $1) { + $is_utf8 = 1 if (!defined $is_utf8); + } + else { + $is_utf8 = 0 if (!defined $is_utf8); + if ($is_utf8) { # eventually, not utf8 + return; + } + } + } + + return $is_utf8; +} + + +1; +__END__ + +=pod + +=head1 NAME + +JSON::PP56 - Helper module in using JSON::PP in Perl 5.6 + +=head1 DESCRIPTION + +JSON::PP calls internally. + +=head1 AUTHOR + +Makamaka Hannyaharamitu, E<lt>makamaka[at]cpan.orgE<gt> + + +=head1 COPYRIGHT AND LICENSE + +Copyright 2007-2012 by Makamaka Hannyaharamitu + +This library is free software; you can redistribute it and/or modify +it under the same terms as Perl itself. + +=cut + diff --git a/t/00_backend_version.t b/t/00_backend_version.t new file mode 100644 index 0000000..b55e13f --- /dev/null +++ b/t/00_backend_version.t @@ -0,0 +1,7 @@ +use Test::More tests => 1; +use strict; +BEGIN { $ENV{PERL_JSON_BACKEND} ||= "JSON::backportPP"; } + +use JSON; +diag ($JSON::BackendModule.' '.$JSON::BackendModule->VERSION); +ok 1; diff --git a/t/00_load.t b/t/00_load.t new file mode 100644 index 0000000..4409ce1 --- /dev/null +++ b/t/00_load.t @@ -0,0 +1,9 @@ +# copied over from JSON::XS and modified to use JSON + +BEGIN { $| = 1; print "1..1\n"; } +END {print "not ok 1\n" unless $loaded;} +BEGIN { $ENV{PERL_JSON_BACKEND} ||= "JSON::backportPP"; } + +use JSON; +$loaded = 1; +print "ok 1\n"; diff --git a/t/00_load_backport_pp.t b/t/00_load_backport_pp.t new file mode 100644 index 0000000..ba4ce43 --- /dev/null +++ b/t/00_load_backport_pp.t @@ -0,0 +1,15 @@ +use Test::More; +use strict; +BEGIN { plan tests => 5 }; + +BEGIN { $ENV{PERL_JSON_BACKEND} = "JSON::backportPP"; } + +BEGIN { + use_ok('JSON'); +} + +ok( exists $INC{ 'JSON/backportPP.pm' }, 'load backportPP' ); +ok( ! exists $INC{ 'JSON/PP.pm' }, q/didn't load PP/ ); + +ok( JSON->backend->isa('JSON::PP') ); +ok( JSON->backend->is_pp ); diff --git a/t/00_pod.t b/t/00_pod.t new file mode 100644 index 0000000..e8e3082 --- /dev/null +++ b/t/00_pod.t @@ -0,0 +1,8 @@ +use strict; +$^W = 1; + +use Test::More; + +eval "use Test::Pod 1.00"; +plan skip_all => "Test::Pod 1.00 required for testing POD" if $@; +all_pod_files_ok (); diff --git a/t/01_utf8.t b/t/01_utf8.t new file mode 100644 index 0000000..dccefa5 --- /dev/null +++ b/t/01_utf8.t @@ -0,0 +1,25 @@ +# copied over from JSON::XS and modified to use JSON + +use strict; +use Test::More; +BEGIN { plan tests => 9 }; + +BEGIN { $ENV{PERL_JSON_BACKEND} ||= "JSON::backportPP"; } + +use utf8; +use JSON; + + +ok (JSON->new->allow_nonref (1)->utf8 (1)->encode ("ü") eq "\"\xc3\xbc\""); +ok (JSON->new->allow_nonref (1)->encode ("ü") eq "\"ü\""); +ok (JSON->new->allow_nonref (1)->ascii (1)->utf8 (1)->encode (chr 0x8000) eq '"\u8000"'); +ok (JSON->new->allow_nonref (1)->ascii (1)->utf8 (1)->pretty (1)->encode (chr 0x10402) eq "\"\\ud801\\udc02\"\n"); + +eval { JSON->new->allow_nonref (1)->utf8 (1)->decode ('"ü"') }; +ok $@ =~ /malformed UTF-8/; + +ok (JSON->new->allow_nonref (1)->decode ('"ü"') eq "ü"); +ok (JSON->new->allow_nonref (1)->decode ('"\u00fc"') eq "ü"); +ok (JSON->new->allow_nonref (1)->decode ('"\ud801\udc02' . "\x{10204}\"") eq "\x{10402}\x{10204}"); +ok (JSON->new->allow_nonref (1)->decode ('"\"\n\\\\\r\t\f\b"') eq "\"\012\\\015\011\014\010"); + diff --git a/t/02_error.t b/t/02_error.t new file mode 100644 index 0000000..a362302 --- /dev/null +++ b/t/02_error.t @@ -0,0 +1,55 @@ +# copied over from JSON::XS and modified to use JSON + +use strict; +use Test::More; +BEGIN { plan tests => 35 }; + +BEGIN { $ENV{PERL_JSON_BACKEND} ||= "JSON::backportPP"; } + +use utf8; +use JSON; +no warnings; + + +eval { JSON->new->encode ([\-1]) }; ok $@ =~ /cannot encode reference/; +eval { JSON->new->encode ([\undef]) }; ok $@ =~ /cannot encode reference/; +eval { JSON->new->encode ([\2]) }; ok $@ =~ /cannot encode reference/; +eval { JSON->new->encode ([\{}]) }; ok $@ =~ /cannot encode reference/; +eval { JSON->new->encode ([\[]]) }; ok $@ =~ /cannot encode reference/; +eval { JSON->new->encode ([\\1]) }; ok $@ =~ /cannot encode reference/; + +eval { JSON->new->allow_nonref (1)->decode ('"\u1234\udc00"') }; ok $@ =~ /missing high /; +eval { JSON->new->allow_nonref->decode ('"\ud800"') }; ok $@ =~ /missing low /; +eval { JSON->new->allow_nonref (1)->decode ('"\ud800\u1234"') }; ok $@ =~ /surrogate pair /; + +eval { JSON->new->allow_nonref (0)->decode ('null') }; ok $@ =~ /allow_nonref/; +eval { JSON->new->allow_nonref (1)->decode ('+0') }; ok $@ =~ /malformed/; +eval { JSON->new->allow_nonref->decode ('.2') }; ok $@ =~ /malformed/; +eval { JSON->new->allow_nonref (1)->decode ('bare') }; ok $@ =~ /malformed/; +eval { JSON->new->allow_nonref->decode ('naughty') }; ok $@ =~ /null/; +eval { JSON->new->allow_nonref (1)->decode ('01') }; ok $@ =~ /leading zero/; +eval { JSON->new->allow_nonref->decode ('00') }; ok $@ =~ /leading zero/; +eval { JSON->new->allow_nonref (1)->decode ('-0.') }; ok $@ =~ /decimal point/; +eval { JSON->new->allow_nonref->decode ('-0e') }; ok $@ =~ /exp sign/; +eval { JSON->new->allow_nonref (1)->decode ('-e+1') }; ok $@ =~ /initial minus/; +eval { JSON->new->allow_nonref->decode ("\"\n\"") }; ok $@ =~ /invalid character/; +eval { JSON->new->allow_nonref (1)->decode ("\"\x01\"") }; ok $@ =~ /invalid character/; +eval { JSON->new->decode ('[5') }; ok $@ =~ /parsing array/; +eval { JSON->new->decode ('{"5"') }; ok $@ =~ /':' expected/; +eval { JSON->new->decode ('{"5":null') }; ok $@ =~ /parsing object/; + +eval { JSON->new->decode (undef) }; ok $@ =~ /malformed/; +eval { JSON->new->decode (\5) }; ok !!$@; # Can't coerce readonly +eval { JSON->new->decode ([]) }; ok $@ =~ /malformed/; +eval { JSON->new->decode (\*STDERR) }; ok $@ =~ /malformed/; +eval { JSON->new->decode (*STDERR) }; ok !!$@; # cannot coerce GLOB + +eval { decode_json ("\"\xa0") }; ok $@ =~ /malformed.*character/; +eval { decode_json ("\"\xa0\"") }; ok $@ =~ /malformed.*character/; +SKIP: { skip "requires JSON::XS 4 compat backend", 4 if ($JSON::BackendModulePP and eval $JSON::BackendModulePP->VERSION < 3) or ($JSON::BackendModule eq 'Cpanel::JSON::XS') or ($JSON::BackendModule eq 'JSON::XS' and $JSON::BackendModule->VERSION < 4); +eval { decode_json ("1\x01") }; ok $@ =~ /garbage after/; +eval { decode_json ("1\x00") }; ok $@ =~ /garbage after/; +eval { decode_json ("\"\"\x00") }; ok $@ =~ /garbage after/; +eval { decode_json ("[]\x00") }; ok $@ =~ /garbage after/; +} + diff --git a/t/03_types.t b/t/03_types.t new file mode 100644 index 0000000..1d98332 --- /dev/null +++ b/t/03_types.t @@ -0,0 +1,63 @@ +# copied over from JSON::XS and modified to use JSON + +use strict; +use Test::More; +BEGIN { plan tests => 76 + 2 }; + +BEGIN { $ENV{PERL_JSON_BACKEND} ||= "JSON::backportPP"; } + +use utf8; +use JSON; + + +ok (!defined JSON->new->allow_nonref (1)->decode ('null')); +ok (JSON->new->allow_nonref (1)->decode ('true') == 1); +ok (JSON->new->allow_nonref (1)->decode ('false') == 0); + +my $true = JSON->new->allow_nonref (1)->decode ('true'); +ok ($true eq 1); +ok (JSON::is_bool $true); +my $false = JSON->new->allow_nonref (1)->decode ('false'); +ok ($false == !$true); +ok (JSON::is_bool $false); +ok (++$false == 1); +ok (!JSON::is_bool $false); +ok (!JSON::is_bool "JSON::Boolean"); +ok (!JSON::is_bool {}); # GH-34 + +ok (JSON->new->allow_nonref (1)->decode ('5') == 5); +ok (JSON->new->allow_nonref (1)->decode ('-5') == -5); +ok (JSON->new->allow_nonref (1)->decode ('5e1') == 50); +ok (JSON->new->allow_nonref (1)->decode ('-333e+0') == -333); +ok (JSON->new->allow_nonref (1)->decode ('2.5') == 2.5); + +ok (JSON->new->allow_nonref (1)->decode ('""') eq ""); +ok ('[1,2,3,4]' eq encode_json decode_json ('[1,2, 3,4]')); +ok ('[{},[],[],{}]' eq encode_json decode_json ('[{},[], [ ] ,{ }]')); +ok ('[{"1":[5]}]' eq encode_json [{1 => [5]}]); +ok ('{"1":2,"3":4}' eq JSON->new->canonical (1)->encode (decode_json '{ "1" : 2, "3" : 4 }')); +ok ('{"1":2,"3":1.2}' eq JSON->new->canonical (1)->encode (decode_json '{ "1" : 2, "3" : 1.2 }')); + +ok ('[true]' eq encode_json [JSON::true]); +ok ('[false]' eq encode_json [JSON::false]); +ok ('[true]' eq encode_json [\1]); +ok ('[false]' eq encode_json [\0]); +ok ('[null]' eq encode_json [undef]); +ok ('[true]' eq encode_json [JSON::true]); +ok ('[false]' eq encode_json [JSON::false]); + +for my $v (1, 2, 3, 5, -1, -2, -3, -4, 100, 1000, 10000, -999, -88, -7, 7, 88, 999, -1e5, 1e6, 1e7, 1e8) { + ok ($v == ((decode_json "[$v]")->[0])); + ok ($v == ((decode_json encode_json [$v])->[0])); +} + +ok (30123 == ((decode_json encode_json [30123])->[0])); +ok (32123 == ((decode_json encode_json [32123])->[0])); +ok (32456 == ((decode_json encode_json [32456])->[0])); +ok (32789 == ((decode_json encode_json [32789])->[0])); +ok (32767 == ((decode_json encode_json [32767])->[0])); +ok (32768 == ((decode_json encode_json [32768])->[0])); + +my @sparse; @sparse[0,3] = (1, 4); +ok ("[1,null,null,4]" eq encode_json \@sparse); + diff --git a/t/04_dwiw_encode.t b/t/04_dwiw_encode.t new file mode 100644 index 0000000..14a30dd --- /dev/null +++ b/t/04_dwiw_encode.t @@ -0,0 +1,71 @@ +# copied over from JSON::XS and modified to use JSON + +# copied over from JSON::DWIW and modified to use JSON + +# Creation date: 2007-02-20 19:51:06 +# Authors: don + +use strict; +use Test; + +# main +{ + BEGIN { plan tests => 5 } + + BEGIN { $ENV{PERL_JSON_BACKEND} ||= "JSON::backportPP"; } + +use JSON; + + my $data; + + # my $expected_str = '{"var1":"val1","var2":["first_element",{"sub_element":"sub_val","sub_element2":"sub_val2"}],"var3":"val3"}'; + + my $expected_str1 = '{"var1":"val1","var2":["first_element",{"sub_element":"sub_val","sub_element2":"sub_val2"}]}'; + my $expected_str2 = '{"var2":["first_element",{"sub_element":"sub_val","sub_element2":"sub_val2"}],"var1":"val1"}'; + my $expected_str3 = '{"var2":["first_element",{"sub_element2":"sub_val2","sub_element":"sub_val"}],"var1":"val1"}'; + my $expected_str4 = '{"var1":"val1","var2":["first_element",{"sub_element2":"sub_val2","sub_element":"sub_val"}]}'; + + my $json_obj = JSON->new->allow_nonref (1); + my $json_str; + # print STDERR "\n" . $json_str . "\n\n"; + + my $expected_str; + + $data = 'stuff'; + $json_str = $json_obj->encode($data); + ok($json_str eq '"stuff"'); + + $data = "stu\nff"; + $json_str = $json_obj->encode($data); + ok($json_str eq '"stu\nff"'); + + $data = [ 1, 2, 3 ]; + $expected_str = '[1,2,3]'; + $json_str = $json_obj->encode($data); + + ok($json_str eq $expected_str); + + $data = { var1 => 'val1', var2 => 'val2' }; + $json_str = $json_obj->encode($data); + + ok($json_str eq '{"var1":"val1","var2":"val2"}' + or $json_str eq '{"var2":"val2","var1":"val1"}'); + + $data = { var1 => 'val1', + var2 => [ 'first_element', + { sub_element => 'sub_val', sub_element2 => 'sub_val2' }, + ], + # var3 => 'val3', + }; + + $json_str = $json_obj->encode($data); + + ok($json_str eq $expected_str1 or $json_str eq $expected_str2 + or $json_str eq $expected_str3 or $json_str eq $expected_str4); +} + +exit 0; + +############################################################################### +# Subroutines + diff --git a/t/05_dwiw_decode.t b/t/05_dwiw_decode.t new file mode 100644 index 0000000..fb94f20 --- /dev/null +++ b/t/05_dwiw_decode.t @@ -0,0 +1,93 @@ +# copied over from JSON::XS and modified to use JSON + +# copied over from JSON::DWIW and modified to use JSON + +# Creation date: 2007-02-20 21:54:09 +# Authors: don + +use strict; +use warnings; +use Test; + +# main +{ + BEGIN { plan tests => 7 } + + BEGIN { $ENV{PERL_JSON_BACKEND} ||= "JSON::backportPP"; } + +use JSON; + + my $json_str = '{"var1":"val1","var2":["first_element",{"sub_element":"sub_val","sub_element2":"sub_val2"}],"var3":"val3"}'; + + my $json_obj = JSON->new->allow_nonref(1); + my $data = $json_obj->decode($json_str); + + my $pass = 1; + if ($data->{var1} eq 'val1' and $data->{var3} eq 'val3') { + if ($data->{var2}) { + my $array = $data->{var2}; + if (ref($array) eq 'ARRAY') { + if ($array->[0] eq 'first_element') { + my $hash = $array->[1]; + if (ref($hash) eq 'HASH') { + unless ($hash->{sub_element} eq 'sub_val' + and $hash->{sub_element2} eq 'sub_val2') { + $pass = 0; + } + } + else { + $pass = 0; + } + } + else { + $pass = 0; + } + } + else { + $pass = 0; + } + } + else { + $pass = 0; + } + } + + ok($pass); + + $json_str = '"val1"'; + $data = $json_obj->decode($json_str); + ok($data eq 'val1'); + + $json_str = '567'; + $data = $json_obj->decode($json_str); + ok($data == 567); + + $json_str = "5e1"; + $data = $json_obj->decode($json_str); + ok($data == 50); + + $json_str = "5e3"; + $data = $json_obj->decode($json_str); + ok($data == 5000); + + $json_str = "5e+1"; + $data = $json_obj->decode($json_str); + ok($data == 50); + + $json_str = "5e-1"; + $data = $json_obj->decode($json_str); + ok($data == 0.5); + + + + +# use Data::Dumper; +# print STDERR Dumper($test_data) . "\n\n"; + +} + +exit 0; + +############################################################################### +# Subroutines + diff --git a/t/06_pc_pretty.t b/t/06_pc_pretty.t new file mode 100644 index 0000000..333cc7a --- /dev/null +++ b/t/06_pc_pretty.t @@ -0,0 +1,67 @@ +# copied over from JSON::PC and modified to use JSON +# copied over from JSON::XS and modified to use JSON + +use strict; +use Test::More; +BEGIN { plan tests => 9 }; + +BEGIN { $ENV{PERL_JSON_BACKEND} ||= "JSON::backportPP"; } + +use JSON; + +my ($js,$obj,$json); +my $pc = new JSON; + +$obj = {foo => "bar"}; +$js = $pc->encode($obj); +is($js,q|{"foo":"bar"}|); + +$obj = [10, "hoge", {foo => "bar"}]; +$pc->pretty (1); +$js = $pc->encode($obj); +is($js,q|[ + 10, + "hoge", + { + "foo" : "bar" + } +] +|); + +$obj = { foo => [ {a=>"b"}, 0, 1, 2 ] }; +$pc->pretty(0); +$js = $pc->encode($obj); +is($js,q|{"foo":[{"a":"b"},0,1,2]}|); + + +$obj = { foo => [ {a=>"b"}, 0, 1, 2 ] }; +$pc->pretty(1); +$js = $pc->encode($obj); +is($js,q|{ + "foo" : [ + { + "a" : "b" + }, + 0, + 1, + 2 + ] +} +|); + +$obj = { foo => [ {a=>"b"}, 0, 1, 2 ] }; +$pc->pretty(0); +$js = $pc->encode($obj); +is($js,q|{"foo":[{"a":"b"},0,1,2]}|); + + +$obj = {foo => "bar"}; +$pc->indent(1); +is($pc->encode($obj), qq|{\n "foo":"bar"\n}\n|, "nospace"); +$pc->space_after(1); +is($pc->encode($obj), qq|{\n "foo": "bar"\n}\n|, "after"); +$pc->space_before(1); +is($pc->encode($obj), qq|{\n "foo" : "bar"\n}\n|, "both"); +$pc->space_after(0); +is($pc->encode($obj), qq|{\n "foo" :"bar"\n}\n|, "before"); + diff --git a/t/07_pc_esc.t b/t/07_pc_esc.t new file mode 100644 index 0000000..1bb080c --- /dev/null +++ b/t/07_pc_esc.t @@ -0,0 +1,83 @@ +# +# このファイルのエンコーディングはUTF-8 +# + +# copied over from JSON::PC and modified to use JSON +# copied over from JSON::XS and modified to use JSON + +use Test::More; +use strict; +use utf8; +BEGIN { plan tests => 17 }; +BEGIN { $ENV{PERL_JSON_BACKEND} ||= "JSON::backportPP"; } + +use JSON; + +######################### +my ($js,$obj,$str); + +my $pc = new JSON; + +$obj = {test => qq|abc"def|}; +$str = $pc->encode($obj); +is($str,q|{"test":"abc\"def"}|); + +$obj = {qq|te"st| => qq|abc"def|}; +$str = $pc->encode($obj); +is($str,q|{"te\"st":"abc\"def"}|); + +$obj = {test => qq|abc/def|}; # / => \/ +$str = $pc->encode($obj); # but since version 0.99 +is($str,q|{"test":"abc/def"}|); # this handling is deleted. +$obj = $pc->decode($str); +is($obj->{test},q|abc/def|); + +$obj = {test => q|abc\def|}; +$str = $pc->encode($obj); +is($str,q|{"test":"abc\\\\def"}|); + +$obj = {test => "abc\bdef"}; +$str = $pc->encode($obj); +is($str,q|{"test":"abc\bdef"}|); + +$obj = {test => "abc\fdef"}; +$str = $pc->encode($obj); +is($str,q|{"test":"abc\fdef"}|); + +$obj = {test => "abc\ndef"}; +$str = $pc->encode($obj); +is($str,q|{"test":"abc\ndef"}|); + +$obj = {test => "abc\rdef"}; +$str = $pc->encode($obj); +is($str,q|{"test":"abc\rdef"}|); + +$obj = {test => "abc-def"}; +$str = $pc->encode($obj); +is($str,q|{"test":"abc-def"}|); + +$obj = {test => "abc(def"}; +$str = $pc->encode($obj); +is($str,q|{"test":"abc(def"}|); + +$obj = {test => "abc\\def"}; +$str = $pc->encode($obj); +is($str,q|{"test":"abc\\\\def"}|); + +$obj = {test => "あいうえお"}; +$str = $pc->encode($obj); +is($str,q|{"test":"あいうえお"}|); + +$obj = {"あいうえお" => "かきくけこ"}; +$str = $pc->encode($obj); +is($str,q|{"あいうえお":"かきくけこ"}|); + +$obj = $pc->decode(q|{"id":"abc\ndef"}|); +is($obj->{id},"abc\ndef",q|{"id":"abc\ndef"}|); + +$obj = $pc->decode(q|{"id":"abc\\\ndef"}|); +is($obj->{id},"abc\\ndef",q|{"id":"abc\\\ndef"}|); + +$obj = $pc->decode(q|{"id":"abc\\\\\ndef"}|); +is($obj->{id},"abc\\\ndef",q|{"id":"abc\\\\\ndef"}|); + diff --git a/t/08_pc_base.t b/t/08_pc_base.t new file mode 100644 index 0000000..f483ed2 --- /dev/null +++ b/t/08_pc_base.t @@ -0,0 +1,98 @@ +use Test::More; + +# copied over from JSON::PC and modified to use JSON +# copied over from JSON::XS and modified to use JSON + +use strict; +BEGIN { plan tests => 20 }; +BEGIN { $ENV{PERL_JSON_BACKEND} ||= "JSON::backportPP"; } + +use JSON; + +my ($js,$obj); + +my $pc = new JSON; + +$js = q|{}|; + +$obj = $pc->decode($js); +$js = $pc->encode($obj); +is($js,'{}', '{}'); + +$js = q|[]|; +$obj = $pc->decode($js); +$js = $pc->encode($obj); +is($js,'[]', '[]'); + + +$js = q|{"foo":"bar"}|; +$obj = $pc->decode($js); +is($obj->{foo},'bar'); +$js = $pc->encode($obj); +is($js,'{"foo":"bar"}', '{"foo":"bar"}'); + +$js = q|{"foo":""}|; +$obj = $pc->decode($js); +$js = $pc->encode($obj); +is($js,'{"foo":""}', '{"foo":""}'); + +$js = q|{"foo":" "}|; +$obj = $pc->decode($js); +$js = $pc->encode($obj); +is($js,'{"foo":" "}' ,'{"foo":" "}'); + +$js = q|{"foo":"0"}|; +$obj = $pc->decode($js); +$js = $pc->encode($obj); +is($js,'{"foo":"0"}',q|{"foo":"0"} - autoencode (default)|); + + +$js = q|{"foo":"0 0"}|; +$obj = $pc->decode($js); +$js = $pc->encode($obj); +is($js,'{"foo":"0 0"}','{"foo":"0 0"}'); + +$js = q|[1,2,3]|; +$obj = $pc->decode($js); +is($obj->[1],2); +$js = $pc->encode($obj); +is($js,'[1,2,3]'); + +$js = q|{"foo":{"bar":"hoge"}}|; +$obj = $pc->decode($js); +is($obj->{foo}->{bar},'hoge'); +$js = $pc->encode($obj); +is($js,q|{"foo":{"bar":"hoge"}}|); + +$js = q|[{"foo":[1,2,3]},-0.12,{"a":"b"}]|; +$obj = $pc->decode($js); +$js = $pc->encode($obj); +is($js,q|[{"foo":[1,2,3]},-0.12,{"a":"b"}]|); + + +$obj = ["\x01"]; +is($js = $pc->encode($obj),'["\\u0001"]'); +$obj = $pc->decode($js); +is($obj->[0],"\x01"); + +$obj = ["\e"]; +is($js = $pc->encode($obj),'["\\u001b"]'); +$obj = $pc->decode($js); +is($obj->[0],"\e"); + +$js = '{"id":"}'; +eval q{ $pc->decode($js) }; +like($@, qr/unexpected end/i); + +$obj = { foo => sub { "bar" } }; +eval q{ $js = $pc->encode($obj) }; +like($@, qr/JSON can only/i, 'invalid value (coderef)'); + +#$obj = { foo => bless {}, "Hoge" }; +#eval q{ $js = $pc->encode($obj) }; +#like($@, qr/JSON can only/i, 'invalid value (blessd object)'); + +$obj = { foo => \$js }; +eval q{ $js = $pc->encode($obj) }; +like($@, qr/cannot encode reference/i, 'invalid value (ref)'); + diff --git a/t/09_pc_extra_number.t b/t/09_pc_extra_number.t new file mode 100644 index 0000000..697786a --- /dev/null +++ b/t/09_pc_extra_number.t @@ -0,0 +1,38 @@ +# copied over from JSON::PC and modified to use JSON +# copied over from JSON::XS and modified to use JSON + +use Test::More; +use strict; +BEGIN { plan tests => 6 }; +BEGIN { $ENV{PERL_JSON_BACKEND} ||= "JSON::backportPP"; } + +use JSON; +use utf8; + +######################### +my ($js,$obj); +my $pc = new JSON; + +$js = '{"foo":0}'; +$obj = $pc->decode($js); +is($obj->{foo}, 0, "normal 0"); + +$js = '{"foo":0.1}'; +$obj = $pc->decode($js); +is($obj->{foo}, 0.1, "normal 0.1"); + + +$js = '{"foo":10}'; +$obj = $pc->decode($js); +is($obj->{foo}, 10, "normal 10"); + +$js = '{"foo":-10}'; +$obj = $pc->decode($js); +is($obj->{foo}, -10, "normal -10"); + + +$js = '{"foo":0, "bar":0.1}'; +$obj = $pc->decode($js); +is($obj->{foo},0, "normal 0"); +is($obj->{bar},0.1,"normal 0.1"); + diff --git a/t/104_sortby.t b/t/104_sortby.t new file mode 100644 index 0000000..20b087e --- /dev/null +++ b/t/104_sortby.t @@ -0,0 +1,24 @@ + +use Test::More; +use strict; +BEGIN { plan tests => 3 }; +BEGIN { $ENV{PERL_JSON_BACKEND} ||= "JSON::backportPP"; } +use JSON -support_by_pp; +######################### + +my ($js,$obj); +my $pc = JSON->new; + +$obj = {a=>1, b=>2, c=>3, d=>4, e=>5, f=>6, g=>7, h=>8, i=>9}; + +$js = $pc->sort_by(1)->encode($obj); +is($js, q|{"a":1,"b":2,"c":3,"d":4,"e":5,"f":6,"g":7,"h":8,"i":9}|); + + +$js = $pc->sort_by(sub { $JSON::PP::a cmp $JSON::PP::b })->encode($obj); +is($js, q|{"a":1,"b":2,"c":3,"d":4,"e":5,"f":6,"g":7,"h":8,"i":9}|); + +$js = $pc->sort_by('hoge')->encode($obj); +is($js, q|{"a":1,"b":2,"c":3,"d":4,"e":5,"f":6,"g":7,"h":8,"i":9}|); + +sub JSON::PP::hoge { $JSON::PP::a cmp $JSON::PP::b } diff --git a/t/105_esc_slash.t b/t/105_esc_slash.t new file mode 100644 index 0000000..495766e --- /dev/null +++ b/t/105_esc_slash.t @@ -0,0 +1,15 @@ +
+use Test::More;
+use strict;
+BEGIN { plan tests => 2 };
+BEGIN { $ENV{PERL_JSON_BACKEND} ||= "JSON::backportPP"; }
+use JSON -support_by_pp;
+#########################
+
+my $json = JSON->new->allow_nonref;
+
+my $js = '/';
+
+is($json->encode($js), '"/"');
+is($json->escape_slash->encode($js), '"\/"');
+
diff --git a/t/106_allow_barekey.t b/t/106_allow_barekey.t new file mode 100644 index 0000000..042e0bd --- /dev/null +++ b/t/106_allow_barekey.t @@ -0,0 +1,19 @@ +
+use Test::More;
+use strict;
+BEGIN { plan tests => 2 };
+BEGIN { $ENV{PERL_JSON_BACKEND} ||= "JSON::backportPP"; }
+use JSON -support_by_pp;
+#########################
+
+my $json = JSON->new->allow_nonref;
+
+eval q| $json->decode('{foo:"bar"}') |;
+
+ok($@); # in XS and PP, the error message differs.
+
+$json->allow_barekey;
+
+is($json->decode('{foo:"bar"}')->{foo}, 'bar');
+
+
diff --git a/t/107_allow_singlequote.t b/t/107_allow_singlequote.t new file mode 100644 index 0000000..b1f6a6c --- /dev/null +++ b/t/107_allow_singlequote.t @@ -0,0 +1,20 @@ +
+use Test::More;
+use strict;
+BEGIN { plan tests => 4 };
+BEGIN { $ENV{PERL_JSON_BACKEND} ||= "JSON::backportPP"; }
+use JSON -support_by_pp;
+#########################
+
+my $json = JSON->new->allow_nonref;
+
+eval q| $json->decode("{'foo':'bar'}") |;
+
+ok($@); # in XS and PP, the error message differs.
+
+$json->allow_singlequote;
+
+is($json->decode(q|{'foo':"bar"}|)->{foo}, 'bar');
+is($json->decode(q|{'foo':'bar'}|)->{foo}, 'bar');
+is($json->allow_barekey->decode(q|{foo:'bar'}|)->{foo}, 'bar');
+
diff --git a/t/108_decode.t b/t/108_decode.t new file mode 100644 index 0000000..7e1e547 --- /dev/null +++ b/t/108_decode.t @@ -0,0 +1,36 @@ +# +# decode on Perl 5.005, 5.6, 5.8 or later +# +use strict; +use Test::More; + +BEGIN { plan tests => 6 }; + +BEGIN { $ENV{PERL_JSON_BACKEND} ||= "JSON::backportPP"; } + +use JSON; + +no utf8; + +my $json = JSON->new->allow_nonref; + + +is($json->decode(q|"ü"|), "ü"); # utf8 +is($json->decode(q|"\u00fc"|), "\xfc"); # latin1 +is($json->decode(q|"\u00c3\u00bc"|), "\xc3\xbc"); # utf8 + +my $str = 'あ'; # Japanese 'a' in utf8 + +is($json->decode(q|"\u00e3\u0081\u0082"|), $str); + +utf8::decode($str); # usually UTF-8 flagged on, but no-op for 5.005. + +is($json->decode(q|"\u3042"|), $str); + + +my $utf8 = $json->decode(q|"\ud808\udf45"|); # chr 12345 + +utf8::encode($utf8); # UTF-8 flagged off + +is($utf8, "\xf0\x92\x8d\x85"); + diff --git a/t/109_encode.t b/t/109_encode.t new file mode 100644 index 0000000..c189297 --- /dev/null +++ b/t/109_encode.t @@ -0,0 +1,34 @@ +# +# decode on Perl 5.005, 5.6, 5.8 or later +# +use strict; +use Test::More; + +BEGIN { plan tests => 7 }; + +BEGIN { $ENV{PERL_JSON_BACKEND} ||= "JSON::backportPP"; } + +use JSON; + +no utf8; + +my $json = JSON->new->allow_nonref; + +is($json->encode("ü"), q|"ü"|); # as is + +$json->ascii; + +is($json->encode("\xfc"), q|"\u00fc"|); # latin1 +is($json->encode("\xc3\xbc"), q|"\u00c3\u00bc"|); # utf8 +is($json->encode("ü"), q|"\u00c3\u00bc"|); # utf8 +is($json->encode('あ'), q|"\u00e3\u0081\u0082"|); + +if ($] >= 5.006) { + is($json->encode(chr hex 3042 ), q|"\u3042"|); + is($json->encode(chr hex 12345 ), q|"\ud808\udf45"|); +} +else { + is($json->encode(chr hex 3042 ), $json->encode(chr 66)); + is($json->encode(chr hex 12345 ), $json->encode(chr 69)); +} + diff --git a/t/10_pc_keysort.t b/t/10_pc_keysort.t new file mode 100644 index 0000000..5dc42ac --- /dev/null +++ b/t/10_pc_keysort.t @@ -0,0 +1,19 @@ +# copied over from JSON::PC and modified to use JSON +# copied over from JSON::XS and modified to use JSON + +use Test::More; +use strict; +BEGIN { plan tests => 1 }; +BEGIN { $ENV{PERL_JSON_BACKEND} ||= "JSON::backportPP"; } + +use JSON; +######################### + +my ($js,$obj); +my $pc = JSON->new->canonical(1); + +$obj = {a=>1, b=>2, c=>3, d=>4, e=>5, f=>6, g=>7, h=>8, i=>9}; + +$js = $pc->encode($obj); +is($js, q|{"a":1,"b":2,"c":3,"d":4,"e":5,"f":6,"g":7,"h":8,"i":9}|); + diff --git a/t/110_bignum.t b/t/110_bignum.t new file mode 100644 index 0000000..044e0e6 --- /dev/null +++ b/t/110_bignum.t @@ -0,0 +1,50 @@ + +use strict; +use Test::More; +BEGIN { plan tests => 9 }; + +BEGIN { $ENV{PERL_JSON_BACKEND} ||= "JSON::backportPP"; } + +use JSON -support_by_pp; + +eval q| require Math::BigInt |; + +SKIP: { + skip "Can't load Math::BigInt.", 9 if ($@); + + my $v = Math::BigInt->VERSION; + $v =~ s/_.+$// if $v; + +my $fix = !$v ? '+' + : $v < 1.6 ? '+' + : ''; + + +my $json = new JSON; + +$json->allow_nonref->allow_bignum(1); +$json->convert_blessed->allow_blessed; + +my $num = $json->decode(q|100000000000000000000000000000000000000|); + +ok($num->isa('Math::BigInt')); +is("$num", $fix . '100000000000000000000000000000000000000'); +is($json->encode($num), $fix . '100000000000000000000000000000000000000'); + +SKIP: { skip "requires $JSON::BackendModule 2.91_03 or newer", 2 if $JSON::BackendModulePP and eval $JSON::BackendModulePP->VERSION < 2.91_03; +$num = $json->decode(q|10|); + +ok(!(ref $num and $num->isa('Math::BigInt')), 'small integer is not a BigInt'); +ok(!(ref $num and $num->isa('Math::BigFloat')), 'small integer is not a BigFloat'); +} + +$num = $json->decode(q|2.0000000000000000001|); + +ok($num->isa('Math::BigFloat')); +is("$num", '2.0000000000000000001'); +is($json->encode($num), '2.0000000000000000001'); + +SKIP: { skip "requires $JSON::BackendModule 2.90 or newer", 1 if $JSON::BackendModulePP and eval $JSON::BackendModulePP->VERSION < 2.90; +is($json->encode([Math::BigInt->new("0")]), "[${fix}0]", "zero bigint is 0 (the number), not '0' (the string)" ); +} +} diff --git a/t/112_upgrade.t b/t/112_upgrade.t new file mode 100644 index 0000000..94b6d1f --- /dev/null +++ b/t/112_upgrade.t @@ -0,0 +1,24 @@ +use strict; +use Test::More; + +BEGIN { plan tests => 3 }; + +BEGIN { $ENV{PERL_JSON_BACKEND} ||= "JSON::backportPP"; } + +use JSON; + +my $json = JSON->new->allow_nonref->utf8; +my $str = '\\u00c8'; + +my $value = $json->decode( '"\\u00c8"' ); + +#use Devel::Peek; +#Dump( $value ); + +is( $value, chr 0xc8 ); + +ok( utf8::is_utf8( $value ) ); + +eval { $json->decode( '"' . chr(0xc8) . '"' ) }; +ok( $@ =~ /malformed UTF-8 character in JSON string/ ); + diff --git a/t/113_overloaded_eq.t b/t/113_overloaded_eq.t new file mode 100644 index 0000000..f9bc8e8 --- /dev/null +++ b/t/113_overloaded_eq.t @@ -0,0 +1,66 @@ +use strict; +use Test::More tests => 4; + +BEGIN { + $ENV{ PERL_JSON_BACKEND } = 0; +} + +BEGIN { $ENV{PERL_JSON_BACKEND} ||= "JSON::backportPP"; } + +use JSON; + +my $json = JSON->new->convert_blessed; + +my $obj = OverloadedObject->new( 'foo' ); +ok( $obj eq 'foo' ); +is( $json->encode( [ $obj ] ), q{["foo"]} ); + +# rt.cpan.org #64783 +my $foo = bless {}, 'Foo'; +my $bar = bless {}, 'Bar'; + +eval q{ $json->encode( $foo ) }; +ok($@); +eval q{ $json->encode( $bar ) }; +ok(!$@); + + +package Foo; + +use strict; +use overload ( + 'eq' => sub { 0 }, + '""' => sub { $_[0] }, + fallback => 1, +); + +sub TO_JSON { + return $_[0]; +} + +package Bar; + +use strict; +use overload ( + 'eq' => sub { 0 }, + '""' => sub { $_[0] }, + fallback => 1, +); + +sub TO_JSON { + return overload::StrVal($_[0]); +} + + +package OverloadedObject; + +use overload 'eq' => sub { $_[0]->{v} eq $_[1] }, '""' => sub { $_[0]->{v} }, fallback => 1; + + +sub new { + bless { v => $_[1] }, $_[0]; +} + + +sub TO_JSON { "$_[0]"; } + diff --git a/t/114_decode_prefix.t b/t/114_decode_prefix.t new file mode 100644 index 0000000..78db21e --- /dev/null +++ b/t/114_decode_prefix.t @@ -0,0 +1,29 @@ +use strict; +use Test::More tests => 8; + +BEGIN { + $ENV{ PERL_JSON_BACKEND } = 0; +} + +BEGIN { $ENV{PERL_JSON_BACKEND} ||= "JSON::backportPP"; } + +use JSON; + +my $json = JSON->new; + +my $complete_text = qq/{"foo":"bar"}/; +my $garbaged_text = qq/{"foo":"bar"}\n/; +my $garbaged_text2 = qq/{"foo":"bar"}\n\n/; +my $garbaged_text3 = qq/{"foo":"bar"}\n----/; + +is( ( $json->decode_prefix( $complete_text ) ) [1], 13 ); +is( ( $json->decode_prefix( $garbaged_text ) ) [1], 13 ); +is( ( $json->decode_prefix( $garbaged_text2 ) ) [1], 13 ); +is( ( $json->decode_prefix( $garbaged_text3 ) ) [1], 13 ); + +eval { $json->decode( "\n" ) }; ok( $@ =~ /malformed JSON/ ); +eval { $json->allow_nonref(0)->decode('null') }; ok $@ =~ /allow_nonref/; + +eval { $json->decode_prefix( "\n" ) }; ok( $@ =~ /malformed JSON/ ); +eval { $json->allow_nonref(0)->decode_prefix('null') }; ok $@ =~ /allow_nonref/; + diff --git a/t/115_tie_ixhash.t b/t/115_tie_ixhash.t new file mode 100644 index 0000000..95920e0 --- /dev/null +++ b/t/115_tie_ixhash.t @@ -0,0 +1,46 @@ + +use strict; +use Test::More; +BEGIN { plan tests => 2 }; + +BEGIN { $ENV{PERL_JSON_BACKEND} ||= "JSON::backportPP"; } + +use JSON; + +# from https://rt.cpan.org/Ticket/Display.html?id=25162 + +SKIP: { + eval {require Tie::IxHash}; + skip "Can't load Tie::IxHash.", 2 if ($@); + + my %columns; + tie %columns, 'Tie::IxHash'; + + %columns = ( + id => 'int', + 1 => 'a', + 2 => 'b', + 3 => 'c', + 4 => 'd', + 5 => 'e', + ); + + my $json = JSON->new; + + my $js = $json->encode(\%columns); + is( $js, q/{"id":"int","1":"a","2":"b","3":"c","4":"d","5":"e"}/ ); + + $js = $json->pretty->encode(\%columns); + is( $js, <<'STR' ); +{ + "id" : "int", + "1" : "a", + "2" : "b", + "3" : "c", + "4" : "d", + "5" : "e" +} +STR + +} + diff --git a/t/116_incr_parse_fixed.t b/t/116_incr_parse_fixed.t new file mode 100644 index 0000000..7bbee2f --- /dev/null +++ b/t/116_incr_parse_fixed.t @@ -0,0 +1,25 @@ +use strict; +use Test::More tests => 4; + +BEGIN { $ENV{PERL_JSON_BACKEND} ||= "JSON::backportPP"; } + +use JSON; + +my $json = JSON->new->allow_nonref(1); + +my @vs = $json->incr_parse('"a\"bc'); + +ok( not scalar(@vs) ); + +@vs = $json->incr_parse('"'); + +is( $vs[0], "a\"bc" ); + + +$json = JSON->new->allow_nonref(0); + +@vs = $json->incr_parse('"a\"bc'); +ok( not scalar(@vs) ); +@vs = eval { $json->incr_parse('"') }; +ok($@ =~ qr/JSON text must be an object or array/); + diff --git a/t/117_numbers.t b/t/117_numbers.t new file mode 100644 index 0000000..6eed93d --- /dev/null +++ b/t/117_numbers.t @@ -0,0 +1,24 @@ +use Test::More; +use strict; +BEGIN { $ENV{PERL_JSON_BACKEND} ||= "JSON::backportPP"; } +BEGIN { $ENV{PERL_JSON_PP_USE_B} = 0 } +use JSON; + +BEGIN { plan skip_all => "requires $JSON::BackendModule 2.90 or newer" if JSON->backend->is_pp and eval $JSON::BackendModule->VERSION < 2.90 } +BEGIN { plan skip_all => "not for $JSON::BackendModule" if $JSON::BackendModule eq 'JSON::XS' } + +BEGIN { plan tests => 3 } + +# TODO ("inf"/"nan" representations are not portable) +# is encode_json([9**9**9]), '["inf"]'; +# is encode_json([-sin(9**9**9)]), '["nan"]'; + +my $num = 3; +my $str = "$num"; +is encode_json({test => [$num, $str]}), '{"test":[3,"3"]}'; +$num = 3.21; +$str = "$num"; +is encode_json({test => [$num, $str]}), '{"test":[3.21,"3.21"]}'; +$str = '0 but true'; +$num = 1 + $str; +is encode_json({test => [$num, $str]}), '{"test":[1,"0 but true"]}'; diff --git a/t/118_boolean_values.t b/t/118_boolean_values.t new file mode 100644 index 0000000..32e7390 --- /dev/null +++ b/t/118_boolean_values.t @@ -0,0 +1,82 @@ +use strict; +use Test::More; +BEGIN { $ENV{PERL_JSON_BACKEND} ||= "JSON::backportPP"; } +use JSON; + +BEGIN { plan skip_all => "requires Perl 5.008 or later" if $] < 5.008 } + +BEGIN { plan skip_all => "requires JSON::XS 4 compat backend" if ($JSON::BackendModulePP and eval $JSON::BackendModulePP->VERSION < 3) or ($JSON::BackendModule eq 'Cpanel::JSON::XS') or ($JSON::BackendModule eq 'JSON::XS' and $JSON::BackendModule->VERSION < 4); } + +package # + Dummy::True; +*Dummy::True:: = *JSON::PP::Boolean::; + +package # + Dummy::False; +*Dummy::False:: = *JSON::PP::Boolean::; + +package main; + +my $dummy_true = bless \(my $dt = 1), 'Dummy::True'; +my $dummy_false = bless \(my $df = 0), 'Dummy::False'; + +my @tests = ([$dummy_true, $dummy_false, 'Dummy::True', 'Dummy::False']); + +# extra boolean classes +if (eval "require boolean; 1") { + push @tests, [boolean::true(), boolean::false(), 'boolean', 'boolean', 1]; +} +if (eval "require JSON; 1") { + push @tests, [JSON::true(), JSON::false(), 'JSON::PP::Boolean', 'JSON::PP::Boolean']; + push @tests, [JSON->boolean(11), JSON->boolean(undef), 'JSON::PP::Boolean', 'JSON::PP::Boolean']; + push @tests, [JSON::boolean(11), JSON::boolean(undef), 'JSON::PP::Boolean', 'JSON::PP::Boolean']; +} +if (eval "require Data::Bool; 1") { + push @tests, [Data::Bool::true(), Data::Bool::false(), 'Data::Bool::Impl', 'Data::Bool::Impl']; +} +if (eval "require Types::Serialiser; 1") { + push @tests, [Types::Serialiser::true(), Types::Serialiser::false(), 'Types::Serialiser::BooleanBase', 'Types::Serialiser::BooleanBase']; +} + +plan tests => 13 * @tests; + +my $json = JSON->new; +for my $test (@tests) { + my ($true, $false, $true_class, $false_class, $incompat) = @$test; + + $json->boolean_values($false, $true); + my ($new_false, $new_true) = $json->get_boolean_values; + ok defined $new_true, "new true class is defined"; + ok defined $new_false, "new false class is defined"; + ok $new_true->isa($true_class), "new true class is $true_class"; + ok $new_false->isa($false_class), "new false class is $false_class"; + SKIP: { + skip "$true_class is not compatible with JSON::PP::Boolean", 2 if $incompat; + ok $new_true->isa('JSON::PP::Boolean'), "new true class is also JSON::PP::Boolean"; + ok $new_false->isa('JSON::PP::Boolean'), "new false class is also JSON::PP::Boolean"; + } + + my $should_true = $json->allow_nonref(1)->decode('true'); + ok $should_true->isa($true_class), "JSON true turns into a $true_class object"; + + my $should_false = $json->allow_nonref(1)->decode('false'); + ok $should_false->isa($false_class), "JSON false turns into a $false_class object"; + + SKIP: { + skip "$true_class is not compatible with JSON::PP::Boolean", 2 if $incompat; + my $should_true_json = eval { $json->allow_nonref(1)->encode($new_true); }; + is $should_true_json => 'true', "A $true_class object turns into JSON true"; + + my $should_false_json = eval { $json->allow_nonref(1)->encode($new_false); }; + is $should_false_json => 'false', "A $false_class object turns into JSON false"; + } + + $json->boolean_values(); + ok !$json->get_boolean_values, "reset boolean values"; + + $should_true = $json->allow_nonref(1)->decode('true'); + ok $should_true->isa('JSON::PP::Boolean'), "JSON true turns into a JSON::PP::Boolean object"; + + $should_false = $json->allow_nonref(1)->decode('false'); + ok $should_false->isa('JSON::PP::Boolean'), "JSON false turns into a JSON::PP::Boolean object"; +} diff --git a/t/11_pc_expo.t b/t/11_pc_expo.t new file mode 100644 index 0000000..585290a --- /dev/null +++ b/t/11_pc_expo.t @@ -0,0 +1,57 @@ +# copied over from JSON::PC and modified to use JSON +# copied over from JSON::XS and modified to use JSON + +use Test::More; +use strict; +BEGIN { plan tests => 8 + 2 }; +BEGIN { $ENV{PERL_JSON_BACKEND} ||= "JSON::backportPP"; } + +use JSON; + +######################### +my ($js,$obj); +my $pc = new JSON; + +$js = q|[-12.34]|; +$obj = $pc->decode($js); +is($obj->[0], -12.34, 'digit -12.34'); +$js = $pc->encode($obj); +is($js,'[-12.34]', 'digit -12.34'); + +$js = q|[-1.234e5]|; +$obj = $pc->decode($js); +is($obj->[0], -123400, 'digit -1.234e5'); +SKIP: { skip "not for $JSON::BackendModule", 1 if $JSON::BackendModule eq 'Cpanel::JSON::XS'; +$js = $pc->encode($obj); +is($js,'[-123400]', 'digit -1.234e5'); +} + +$js = q|[1.23E-4]|; +$obj = $pc->decode($js); +is($obj->[0], 0.000123, 'digit 1.23E-4'); +$js = $pc->encode($obj); +is($js,'[0.000123]', 'digit 1.23E-4'); + + +$js = q|[1.01e+30]|; +$obj = $pc->decode($js); +is($obj->[0], 1.01e+30, 'digit 1.01e+30'); +$js = $pc->encode($obj); +like($js,qr/\[(?:1.01[Ee]\+0?30|1010000000000000000000000000000)]/, 'digit 1.01e+30'); # RT-128589 (-Duselongdouble or -Dquadmath) + +my $vax_float = (pack("d",1) =~ /^[\x80\x10]\x40/); + +if ($vax_float) { + # VAX has smaller float range. + $js = q|[1.01e+37]|; + $obj = $pc->decode($js); + is($obj->[0], eval '1.01e+37', 'digit 1.01e+37'); + $js = $pc->encode($obj); + like($js,qr/\[1.01[Ee]\+0?37\]/, 'digit 1.01e+37'); +} else { + $js = q|[1.01e+67]|; # 30 -> 67 ... patched by H.Merijn Brand + $obj = $pc->decode($js); + is($obj->[0], eval '1.01e+67', 'digit 1.01e+67'); + $js = $pc->encode($obj); + like($js,qr/\[1.01[Ee]\+0?67\]/, 'digit 1.01e+67'); +} diff --git a/t/12_blessed.t b/t/12_blessed.t new file mode 100644 index 0000000..f966f43 --- /dev/null +++ b/t/12_blessed.t @@ -0,0 +1,52 @@ +# copied over from JSON::XS and modified to use JSON + +use strict; +use Test::More; +BEGIN { plan tests => 16 }; + +BEGIN { $ENV{PERL_JSON_BACKEND} ||= "JSON::backportPP"; } + +use JSON; + + +my $o1 = bless { a => 3 }, "XX"; +my $o2 = bless \(my $dummy = 1), "YY"; + +sub XX::TO_JSON { + {'__',""} +} + +my $js = JSON->new; + +eval { $js->encode ($o1) }; ok ($@ =~ /allow_blessed/); +eval { $js->encode ($o2) }; ok ($@ =~ /allow_blessed/); +$js->allow_blessed; +ok ($js->encode ($o1) eq "null"); +ok ($js->encode ($o2) eq "null"); +$js->convert_blessed; +ok ($js->encode ($o1) eq '{"__":""}'); +ok ($js->encode ($o2) eq "null"); + +$js->filter_json_object (sub { 5 }); +$js->filter_json_single_key_object (a => sub { shift }); +$js->filter_json_single_key_object (b => sub { 7 }); + +ok ("ARRAY" eq ref $js->decode ("[]")); +ok (5 eq join ":", @{ $js->decode ('[{}]') }); +ok (6 eq join ":", @{ $js->decode ('[{"a":6}]') }); +ok (5 eq join ":", @{ $js->decode ('[{"a":4,"b":7}]') }); + +$js->filter_json_object; +ok (7 == $js->decode ('[{"a":4,"b":7}]')->[0]{b}); +ok (3 eq join ":", @{ $js->decode ('[{"a":3}]') }); + +$js->filter_json_object (sub { }); +ok (7 == $js->decode ('[{"a":4,"b":7}]')->[0]{b}); +ok (9 eq join ":", @{ $js->decode ('[{"a":9}]') }); + +$js->filter_json_single_key_object ("a"); +ok (4 == $js->decode ('[{"a":4}]')->[0]{a}); + +$js->filter_json_single_key_object (a => sub { return; }); # sub {} is not suitable for Perl 5.6 +ok (4 == $js->decode ('[{"a":4}]')->[0]{a}); + diff --git a/t/13_limit.t b/t/13_limit.t new file mode 100644 index 0000000..6493733 --- /dev/null +++ b/t/13_limit.t @@ -0,0 +1,32 @@ +# copied over from JSON::XS and modified to use JSON + +use strict; +use Test::More; +BEGIN { plan tests => 11 }; + +BEGIN { $ENV{PERL_JSON_BACKEND} ||= "JSON::backportPP"; } + +use JSON; + + +my $def = 512; + +my $js = JSON->new; +local $^W; # to silence Deep recursion warnings + +ok (!eval { $js->decode (("[" x ($def + 1)) . ("]" x ($def + 1))) }); +ok (ref $js->decode (("[" x $def) . ("]" x $def))); +ok (ref $js->decode (("{\"\":" x ($def - 1)) . "[]" . ("}" x ($def - 1)))); +ok (!eval { $js->decode (("{\"\":" x $def) . "[]" . ("}" x $def)) }); + +ok (ref $js->max_depth (32)->decode (("[" x 32) . ("]" x 32))); + +ok ($js->max_depth(1)->encode ([])); +ok (!eval { $js->encode ([[]]), 1 }); + +ok ($js->max_depth(2)->encode ([{}])); +ok (!eval { $js->encode ([[{}]]), 1 }); + +ok (eval { ref $js->max_size (8)->decode ("[ ]") }); +eval { $js->max_size (8)->decode ("[ ]") }; ok ($@ =~ /max_size/); + diff --git a/t/14_latin1.t b/t/14_latin1.t new file mode 100644 index 0000000..ceda9db --- /dev/null +++ b/t/14_latin1.t @@ -0,0 +1,18 @@ +# copied over from JSON::XS and modified to use JSON + +use strict; +use Test::More; +BEGIN { plan tests => 4 }; + +BEGIN { $ENV{PERL_JSON_BACKEND} ||= "JSON::backportPP"; } + +use JSON; + +my $pp = JSON->new->latin1->allow_nonref; + +ok ($pp->encode ("\x{12}\x{89} ") eq "\"\\u0012\x{89} \""); +ok ($pp->encode ("\x{12}\x{89}\x{abc}") eq "\"\\u0012\x{89}\\u0abc\""); + +ok ($pp->decode ("\"\\u0012\x{89}\"" ) eq "\x{12}\x{89}"); +ok ($pp->decode ("\"\\u0012\x{89}\\u0abc\"") eq "\x{12}\x{89}\x{abc}"); + diff --git a/t/15_prefix.t b/t/15_prefix.t new file mode 100644 index 0000000..a9c5b2e --- /dev/null +++ b/t/15_prefix.t @@ -0,0 +1,19 @@ +# copied over from JSON::XS and modified to use JSON + +use strict; +use Test::More; +BEGIN { plan tests => 4 }; + +BEGIN { $ENV{PERL_JSON_BACKEND} ||= "JSON::backportPP"; } + +use JSON; + +my $pp = JSON->new->latin1->allow_nonref; + +eval { $pp->decode ("[] ") }; +ok (!$@); +eval { $pp->decode ("[] x") }; +ok ($@); +ok (2 == ($pp->decode_prefix ("[][]"))[1]); +ok (3 == ($pp->decode_prefix ("[1] t"))[1]); + diff --git a/t/16_tied.t b/t/16_tied.t new file mode 100644 index 0000000..2298d7d --- /dev/null +++ b/t/16_tied.t @@ -0,0 +1,24 @@ +# copied over from JSON::XS and modified to use JSON + +use strict; +use Test::More; +BEGIN { plan tests => 2 }; + +BEGIN { $ENV{PERL_JSON_BACKEND} ||= "JSON::backportPP"; } + +use JSON; +use Tie::Hash; +use Tie::Array; + + +my $js = JSON->new; + +tie my %h, 'Tie::StdHash'; +%h = (a => 1); + +ok ($js->encode (\%h) eq '{"a":1}'); + +tie my @a, 'Tie::StdArray'; +@a = (1, 2); + +ok ($js->encode (\@a) eq '[1,2]'); diff --git a/t/17_relaxed.t b/t/17_relaxed.t new file mode 100644 index 0000000..01cf81c --- /dev/null +++ b/t/17_relaxed.t @@ -0,0 +1,24 @@ +# copied over from JSON::XS and modified to use JSON + +use strict; +use Test::More; +BEGIN { plan tests => 8 }; + +BEGIN { $ENV{PERL_JSON_BACKEND} ||= "JSON::backportPP"; } + +use utf8; +use JSON; + + +my $json = JSON->new->relaxed; + +ok ('[1,2,3]' eq encode_json $json->decode (' [1,2, 3]')); +ok ('[1,2,4]' eq encode_json $json->decode ('[1,2, 4 , ]')); +ok (!eval { $json->decode ('[1,2, 3,4,,]') }); +ok (!eval { $json->decode ('[,1]') }); + +ok ('{"1":2}' eq encode_json $json->decode (' {"1":2}')); +ok ('{"1":2}' eq encode_json $json->decode ('{"1":2,}')); +ok (!eval { $json->decode ('{,}') }); + +ok ('[1,2]' eq encode_json $json->decode ("[1#,2\n ,2,# ] \n\t]")); diff --git a/t/18_json_checker.t b/t/18_json_checker.t new file mode 100644 index 0000000..4745a95 --- /dev/null +++ b/t/18_json_checker.t @@ -0,0 +1,175 @@ +# copied over from JSON::XS and modified to use JSON + +# use the testsuite from http://www.json.org/JSON_checker/ +# except for fail18.json, as we do not support a depth of 20 (but 16 and 32). + +use strict; +no warnings; +use Test::More; +BEGIN { plan tests => 38 }; + +BEGIN { $ENV{PERL_JSON_BACKEND} ||= "JSON::backportPP"; } + +use JSON; + +# emulate JSON_checker default config +my $json = JSON->new->utf8->max_depth(32)->canonical; + +my $vax_float = (pack("d",1) =~ /^[\x80\x10]\x40/); + +binmode DATA; + +for (;;) { + $/ = "\n# "; + chomp (my $test = <DATA>) + or last; + $/ = "\n"; + my $name = <DATA>; + if ($vax_float && $name =~ /pass1.json/) { + $test =~ s/\b23456789012E66\b/23456789012E20/; + } + + if (my $perl = eval { $json->decode ($test) }) { + ok ($name =~ /^pass/, $name); + is ($json->encode ($json->decode ($json->encode ($perl))), $json->encode ($perl)); + } else { + ok ($name =~ /^fail/, "$name ($@)"); + } +} + +__DATA__ +{"Extra value after close": true} "misplaced quoted value" +# fail10.json +{"Illegal expression": 1 + 2} +# fail11.json +{"Illegal invocation": alert()} +# fail12.json +{"Numbers cannot have leading zeroes": 013} +# fail13.json +{"Numbers cannot be hex": 0x14} +# fail14.json +["Illegal backslash escape: \x15"] +# fail15.json +[\naked] +# fail16.json +["Illegal backslash escape: \017"] +# fail17.json +[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[["Too deep"]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]] +# fail18.json +{"Missing colon" null} +# fail19.json +["Unclosed array" +# fail2.json +{"Double colon":: null} +# fail20.json +{"Comma instead of colon", null} +# fail21.json +["Colon instead of comma": false] +# fail22.json +["Bad value", truth] +# fail23.json +['single quote'] +# fail24.json +[" tab character in string "] +# fail25.json +["tab\ character\ in\ string\ "] +# fail26.json +["line +break"] +# fail27.json +["line\ +break"] +# fail28.json +[0e] +# fail29.json +{unquoted_key: "keys must be quoted"} +# fail3.json +[0e+] +# fail30.json +[0e+-1] +# fail31.json +{"Comma instead if closing brace": true, +# fail32.json +["mismatch"} +# fail33.json +["extra comma",] +# fail4.json +["double extra comma",,] +# fail5.json +[ , "<-- missing value"] +# fail6.json +["Comma after the close"], +# fail7.json +["Extra close"]] +# fail8.json +{"Extra comma": true,} +# fail9.json +[ + "JSON Test Pattern pass1", + {"object with 1 member":["array with 1 element"]}, + {}, + [], + -42, + true, + false, + null, + { + "integer": 1234567890, + "real": -9876.543210, + "e": 0.123456789e-12, + "E": 1.234567890E+34, + "": 23456789012E66, + "zero": 0, + "one": 1, + "space": " ", + "quote": "\"", + "backslash": "\\", + "controls": "\b\f\n\r\t", + "slash": "/ & \/", + "alpha": "abcdefghijklmnopqrstuvwyz", + "ALPHA": "ABCDEFGHIJKLMNOPQRSTUVWYZ", + "digit": "0123456789", + "0123456789": "digit", + "special": "`1~!@#$%^&*()_+-={':[,]}|;.</>?", + "hex": "\u0123\u4567\u89AB\uCDEF\uabcd\uef4A", + "true": true, + "false": false, + "null": null, + "array":[ ], + "object":{ }, + "address": "50 St. James Street", + "url": "http://www.JSON.org/", + "comment": "// /* <!-- --", + "# -- --> */": " ", + " s p a c e d " :[1,2 , 3 + +, + +4 , 5 , 6 ,7 ],"compact":[1,2,3,4,5,6,7], + "jsontext": "{\"object with 1 member\":[\"array with 1 element\"]}", + "quotes": "" \u0022 %22 0x22 034 "", + "\/\\\"\uCAFE\uBABE\uAB98\uFCDE\ubcda\uef4A\b\f\n\r\t`1~!@#$%^&*()_+-=[]{}|;:',./<>?" +: "A key can be any string" + }, + 0.5 ,98.6 +, +99.44 +, + +1066, +1e1, +0.1e1, +1e-1, +1e00,2e+00,2e-00 +,"rosebud"] +# pass1.json +[[[[[[[[[[[[[[[[[[["Not too deep"]]]]]]]]]]]]]]]]]]] +# pass2.json +{ + "JSON Test Pattern pass3": { + "The outermost value": "must be an object or array.", + "In this test": "It is an object." + } +} + +# pass3.json diff --git a/t/19_incr.t b/t/19_incr.t new file mode 100644 index 0000000..6749fd4 --- /dev/null +++ b/t/19_incr.t @@ -0,0 +1,108 @@ +# copied over from JSON::XS and modified to use JSON + +use strict; +no warnings; +use Test::More; +BEGIN { plan tests => 745 }; + +BEGIN { $ENV{PERL_JSON_BACKEND} ||= "JSON::backportPP"; } + +use JSON; + +sub splitter { + my ($coder, $text) = @_; + + # work around hash randomisation bug introduced in 5.18 + $coder->canonical; + + for (0 .. length $text) { + my $a = substr $text, 0, $_; + my $b = substr $text, $_; + + $coder->incr_parse ($a); + $coder->incr_parse ($b); + + my $data = $coder->incr_parse; + #ok (defined $data, "split<$a><$b>"); + ok (defined $data, "split"); + my $e1 = $coder->encode ($data); + my $e2 = $coder->encode ($coder->decode ($text)); + #ok ($e1 eq $e2, "data<$a><$b><$e1><$e2>"); + #ok ($coder->incr_text =~ /^\s*$/, "tailws<$a><$b>"); + ok ($e1 eq $e2, "data"); + ok ($coder->incr_text =~ /^\s*$/, "tailws"); + } +} + +splitter +JSON->new->allow_nonref (0), ' ["x\\"","\\u1000\\\\n\\nx",1,{"\\\\" :5 , "": "x"}]'; +splitter +JSON->new->allow_nonref (0), '[ "x\\"","\\u1000\\\\n\\nx" , 1,{"\\\\ " :5 , "": " x"} ] '; +splitter +JSON->new->allow_nonref (1), '"test"'; +splitter +JSON->new->allow_nonref (1), ' "5" '; +splitter +JSON->new->allow_nonref (1), '-1e5'; +SKIP: { skip "requires $JSON::BackendModule 3 or newer", 33 if $JSON::BackendModulePP and eval $JSON::BackendModulePP->VERSION < 3; +splitter +JSON->new->allow_nonref (1), ' 0.00E+00 '; +} + +{ + my $text = '[5],{"":1} , [ 1,2, 3], {"3":null}'; + my $coder = new JSON; + for (0 .. length $text) { + my $a = substr $text, 0, $_; + my $b = substr $text, $_; + + $coder->incr_parse ($a); + $coder->incr_parse ($b); + + my $j1 = $coder->incr_parse; ok ($coder->incr_text =~ s/^\s*,//, "cskip1"); + my $j2 = $coder->incr_parse; ok ($coder->incr_text =~ s/^\s*,//, "cskip2"); + my $j3 = $coder->incr_parse; ok ($coder->incr_text =~ s/^\s*,//, "cskip3"); + my $j4 = $coder->incr_parse; ok ($coder->incr_text !~ s/^\s*,//, "cskip4"); + my $j5 = $coder->incr_parse; ok ($coder->incr_text !~ s/^\s*,//, "cskip5"); + + ok ('[5]' eq encode_json($j1), "cjson1"); + ok ('{"":1}' eq encode_json($j2), "cjson2"); + ok ('[1,2,3]' eq encode_json($j3), "cjson3"); + ok ('{"3":null}' eq encode_json($j4), "cjson4"); + ok (!defined $j5, "cjson5"); + } +} + +{ + my $text = '[x][5]'; + my $coder = new JSON; + $coder->incr_parse ($text); + ok (!eval { $coder->incr_parse }, "sparse1"); + ok (!eval { $coder->incr_parse }, "sparse2"); + $coder->incr_skip; + ok ('[5]' eq $coder->encode (scalar $coder->incr_parse), "sparse3"); +} + +{ + my $coder = JSON->new->max_size (5); + ok (!$coder->incr_parse ("[ "), "incsize1"); + eval { !$coder->incr_parse ("] ") }; ok ($@ =~ /6 bytes/, "incsize2 $@"); +} + +{ + my $coder = JSON->new->max_depth (3); + ok (!$coder->incr_parse ("[[["), "incdepth1"); + eval { !$coder->incr_parse (" [] ") }; ok ($@ =~ /maximum nesting/, "incdepth2 $@"); +} + +# contributed by yuval kogman, reformatted to fit style +{ + my $coder = JSON->new; + + my $res = eval { $coder->incr_parse("]") }; + my $e = $@; # test more clobbers $@, we need it twice + + ok (!$res, "unbalanced bracket"); + ok ($e, "got error"); + like ($e, qr/malformed/, "malformed json string error"); + + $coder->incr_skip; + + is_deeply (eval { $coder->incr_parse("[42]") }, [42], "valid data after incr_skip"); +} + + diff --git a/t/20_faihu.t b/t/20_faihu.t new file mode 100644 index 0000000..1d6a179 --- /dev/null +++ b/t/20_faihu.t @@ -0,0 +1,32 @@ +# copied over from JSON::XS and modified to use JSON + +# adapted from a test by Aristotle Pagaltzis (http://intertwingly.net/blog/2007/11/15/Astral-Plane-Characters-in-Json) + +use strict; +use warnings; + +BEGIN { $ENV{PERL_JSON_BACKEND} ||= "JSON::backportPP"; } + +BEGIN { if ($] < 5.008) { require Test::More; Test::More::plan(skip_all => "requires Perl 5.8 or later"); } }; + +use JSON; +use Encode qw(encode decode); + +use Test::More tests => 3; + +my ($faihu, $faihu_json, $roundtrip, $js) = "\x{10346}"; + +$js = JSON->new->allow_nonref->ascii; +$faihu_json = $js->encode($faihu); +$roundtrip = $js->decode($faihu_json); +is ($roundtrip, $faihu, 'JSON in ASCII roundtrips correctly'); + +$js = JSON->new->allow_nonref->utf8; +$faihu_json = $js->encode ($faihu); +$roundtrip = $js->decode ($faihu_json); +is ($roundtrip, $faihu, 'JSON in UTF-8 roundtrips correctly'); + +$js = JSON->new->allow_nonref; +$faihu_json = encode 'UTF-16BE', $js->encode ($faihu); +$roundtrip = $js->decode( decode 'UTF-16BE', $faihu_json); +is ($roundtrip, $faihu, 'JSON with external recoding roundtrips correctly' ); diff --git a/t/20_unknown.t b/t/20_unknown.t new file mode 100644 index 0000000..921acae --- /dev/null +++ b/t/20_unknown.t @@ -0,0 +1,53 @@ +use strict; + +use Test::More; +BEGIN { plan tests => 10 }; +BEGIN { $ENV{PERL_JSON_BACKEND} ||= "JSON::backportPP"; } + + +use strict; +use JSON; + +my $json = JSON->new; + +eval q| $json->encode( [ sub {} ] ) |; +ok( $@ =~ /encountered CODE/, $@ ); + +eval q| $json->encode( [ \-1 ] ) |; +ok( $@ =~ /cannot encode reference to scalar/, $@ ); + +eval q| $json->encode( [ \undef ] ) |; +ok( $@ =~ /cannot encode reference to scalar/, $@ ); + +eval q| $json->encode( [ \{} ] ) |; +ok( $@ =~ /cannot encode reference to scalar/, $@ ); + +$json->allow_unknown; + +is( $json->encode( [ sub {} ] ), '[null]' ); +is( $json->encode( [ \-1 ] ), '[null]' ); +is( $json->encode( [ \undef ] ), '[null]' ); +is( $json->encode( [ \{} ] ), '[null]' ); + + +SKIP: { + + skip "this test is for Perl 5.8 or later", 2 if( $] < 5.008 ); + +$json->allow_unknown(0); + +my $fh; +open( $fh, '>hoge.txt' ) or die $!; + +eval q| $json->encode( [ $fh ] ) |; +ok( $@ =~ /encountered GLOB|cannot encode reference to scalar/, $@ ); + +$json->allow_unknown(1); + +is( $json->encode( [ $fh ] ), '[null]' ); + +close $fh; + +unlink('hoge.txt'); + +} diff --git a/t/21_evans.t b/t/21_evans.t new file mode 100644 index 0000000..9136791 --- /dev/null +++ b/t/21_evans.t @@ -0,0 +1,25 @@ +# copied over from JSON::XS and modified to use JSON + +# adapted from a test by Martin Evans + +use strict; +use warnings; + +BEGIN { $ENV{PERL_JSON_BACKEND} ||= "JSON::backportPP"; } + +use JSON; + +print "1..1\n"; + +my $data = ["\x{53f0}\x{6240}\x{306e}\x{6d41}\x{3057}", + "\x{6c60}\x{306e}\x{30ab}\x{30a8}\x{30eb}"]; +my $js = JSON->new->encode ($data); +my $j = new JSON; +my $object = $j->incr_parse ($js); + +die "no object" if !$object; + +eval { $j->incr_text }; + +print $@ ? "not " : "", "ok 1 # $@\n"; + diff --git a/t/22_comment_at_eof.t b/t/22_comment_at_eof.t new file mode 100644 index 0000000..fa26dda --- /dev/null +++ b/t/22_comment_at_eof.t @@ -0,0 +1,50 @@ +# copied over from JSON::XS and modified to use JSON + +# the original test case was provided by IKEGAMI@cpan.org + +use strict; +use warnings; + +use Test::More tests => 13; + +BEGIN { $ENV{PERL_JSON_BACKEND} ||= "JSON::backportPP"; } + +use JSON; + +use Data::Dumper qw( Dumper ); + +sub decoder { + my ($str) = @_; + + my $json = JSON->new->relaxed; + + $json->incr_parse($_[0]); + + my $rv; + if (!eval { $rv = $json->incr_parse(); 1 }) { + $rv = "died with $@"; + } + + local $Data::Dumper::Useqq = 1; + local $Data::Dumper::Terse = 1; + local $Data::Dumper::Indent = 0; + + return Dumper($rv); +} + +is( decoder( "[]" ), '[]', 'array baseline' ); +is( decoder( " []" ), '[]', 'space ignored before array' ); +is( decoder( "\n[]" ), '[]', 'newline ignored before array' ); +is( decoder( "# foo\n[]" ), '[]', 'comment ignored before array' ); +is( decoder( "# fo[o\n[]"), '[]', 'comment ignored before array' ); +is( decoder( "# fo]o\n[]"), '[]', 'comment ignored before array' ); +is( decoder( "[# fo]o\n]"), '[]', 'comment ignored inside array' ); + +is( decoder( "" ), 'undef', 'eof baseline' ); +is( decoder( " " ), 'undef', 'space ignored before eof' ); +is( decoder( "\n" ), 'undef', 'newline ignored before eof' ); +is( decoder( "#,foo\n" ), 'undef', 'comment ignored before eof' ); +is( decoder( "# []o\n" ), 'undef', 'comment ignored before eof' ); + +is( decoder(qq/#\n[#foo\n"#\\n"#\n]/), '["#\n"]', 'array and string in multiple lines' ); + diff --git a/t/52_object.t b/t/52_object.t new file mode 100644 index 0000000..1acf5ea --- /dev/null +++ b/t/52_object.t @@ -0,0 +1,63 @@ +# copied over from JSON::XS and modified to use JSON + +use strict; +use Test::More; +BEGIN { $^W = 0 } # hate + +BEGIN { $ENV{PERL_JSON_BACKEND} ||= "JSON::backportPP"; } + +use JSON; + +my $backend_version = JSON->backend->VERSION; $backend_version =~ s/_//; + +plan skip_all => "allow_tags is not supported" if $backend_version < 3; + +plan tests => 20; + +my $json = JSON->new->convert_blessed->allow_tags->allow_nonref; + +ok (1); + +sub JSON::tojson::TO_JSON { + ok (@_ == 1); + ok (JSON::tojson:: eq ref $_[0]); + ok ($_[0]{k} == 1); + 7 +} + +my $obj = bless { k => 1 }, JSON::tojson::; + +ok (1); + +my $enc = $json->encode ($obj); +ok ($enc eq 7); + +ok (1); + +sub JSON::freeze::FREEZE { + ok (@_ == 2); + ok ($_[1] eq "JSON"); + ok (JSON::freeze:: eq ref $_[0]); + ok ($_[0]{k} == 1); + (3, 1, 2) +} + +sub JSON::freeze::THAW { + ok (@_ == 5); + ok (JSON::freeze:: eq $_[0]); + ok ($_[1] eq "JSON"); + ok ($_[2] == 3); + ok ($_[3] == 1); + ok ($_[4] == 2); + 777 +} + +my $obj = bless { k => 1 }, JSON::freeze::; +my $enc = $json->encode ($obj); +ok ($enc eq '("JSON::freeze")[3,1,2]'); + +my $dec = $json->decode ($enc); +ok ($dec eq 777); + +ok (1); + diff --git a/t/99_binary.t b/t/99_binary.t new file mode 100644 index 0000000..3c19c35 --- /dev/null +++ b/t/99_binary.t @@ -0,0 +1,44 @@ +# copied over from JSON::XS and modified to use JSON + +use strict; +use Test::More; +BEGIN { plan tests => 24576 }; + +BEGIN { $ENV{PERL_JSON_BACKEND} ||= "JSON::backportPP"; } + +use JSON; + + +sub test($) { + my $js; + + $js = JSON->new->allow_nonref(0)->utf8->ascii->shrink->encode ([$_[0]]); + ok ($_[0] eq ((decode_json $js)->[0]), " - 0"); + $js = JSON->new->allow_nonref(0)->utf8->ascii->encode ([$_[0]]); + ok ($_[0] eq (JSON->new->utf8->shrink->decode($js))->[0], " - 1"); + + $js = JSON->new->allow_nonref(0)->utf8->shrink->encode ([$_[0]]); + ok ($_[0] eq ((decode_json $js)->[0]), " - 2"); + $js = JSON->new->allow_nonref(1)->utf8->encode ([$_[0]]); + ok ($_[0] eq (JSON->new->utf8->shrink->decode($js))->[0], " - 3"); + + $js = JSON->new->allow_nonref(1)->ascii->encode ([$_[0]]); + ok ($_[0] eq JSON->new->decode ($js)->[0], " - 4"); + $js = JSON->new->allow_nonref(0)->ascii->encode ([$_[0]]); + ok ($_[0] eq JSON->new->shrink->decode ($js)->[0], " - 5"); + + $js = JSON->new->allow_nonref(1)->shrink->encode ([$_[0]]); + ok ($_[0] eq JSON->new->decode ($js)->[0], " - 6"); + $js = JSON->new->allow_nonref(0)->encode ([$_[0]]); + ok ($_[0] eq JSON->new->shrink->decode ($js)->[0], " - 7"); +} + +srand 0; # doesn't help too much, but its at least more deterministic + +for (1..768) { + test join "", map chr ($_ & 255), 0..$_; + test join "", map chr rand 255, 0..$_; + test join "", map chr ($_ * 97 & ~0x4000), 0..$_; + test join "", map chr (rand (2**20) & ~0x800), 0..$_; +} + diff --git a/t/e00_func.t b/t/e00_func.t new file mode 100644 index 0000000..56f091a --- /dev/null +++ b/t/e00_func.t @@ -0,0 +1,17 @@ +
+use Test::More;
+use strict;
+BEGIN { plan tests => 2 };
+BEGIN { $ENV{PERL_JSON_BACKEND} ||= "JSON::backportPP"; }
+use JSON;
+#########################
+
+my $json = JSON->new;
+
+my $js = 'abc';
+
+
+is(to_json($js, {allow_nonref => 1}), '"abc"');
+
+is(from_json('"abc"', {allow_nonref => 1}), 'abc');
+
diff --git a/t/e01_property.t b/t/e01_property.t new file mode 100644 index 0000000..ce3125c --- /dev/null +++ b/t/e01_property.t @@ -0,0 +1,65 @@ + +use Test::More; +use strict; + +BEGIN { $ENV{PERL_JSON_BACKEND} ||= "JSON::backportPP"; } + +use JSON; + +my @simples = + qw/ascii latin1 utf8 indent canonical space_before space_after allow_nonref shrink allow_blessed + convert_blessed relaxed + /; + +my $json = new JSON; + +# JSON::XS/JSON::PP 4.0 allow nonref by default +my $allow_nonref_by_default = $json->allow_nonref; + +my $has_allow_tags = 0; +if ($json->can('allow_tags') and !ref $json->allow_tags) { + push @simples, 'allow_tags'; + $has_allow_tags = 1; +} + +plan tests => 90 + $has_allow_tags * 7; + +for my $name (@simples) { + my $method = 'get_' . $name; + if ($name eq 'allow_nonref' and $allow_nonref_by_default) { + ok( $json->$method(), $method . ' default'); + } else { + ok(! $json->$method(), $method . ' default'); + } + $json->$name(); + ok($json->$method(), $method . ' set true'); + $json->$name(0); + ok(! $json->$method(), $method . ' set false'); + $json->$name(); + ok($json->$method(), $method . ' set true again'); +} + +ok($json->get_max_depth == 512, 'get_max_depth default'); +$json->max_depth(7); +ok($json->get_max_depth == 7, 'get_max_depth set 7 => 7'); +$json->max_depth(); +ok($json->get_max_depth != 0, 'get_max_depth no arg'); + + +ok($json->get_max_size == 0, 'get_max_size default'); +$json->max_size(7); +ok($json->get_max_size == 7, 'get_max_size set 7 => 7'); +$json->max_size(); +ok($json->get_max_size == 0, 'get_max_size no arg'); + + +for my $name (@simples) { + $json->$name(); + ok($json->property($name), $name); + $json->$name(0); + ok(! $json->property($name), $name); + $json->$name(); + ok($json->property($name), $name); +} + + diff --git a/t/e02_bool.t b/t/e02_bool.t new file mode 100644 index 0000000..06e8dd6 --- /dev/null +++ b/t/e02_bool.t @@ -0,0 +1,45 @@ +use strict; + +use Test::More; +use strict; + +BEGIN { plan tests => 8 }; + +BEGIN { $ENV{PERL_JSON_BACKEND} ||= "JSON::backportPP"; } + +use JSON; + +my $json = new JSON; + +diag $json->backend->isa('JSON::PP'); +my $not_not_a_number_is_a_number = ( + $json->backend->isa('Cpanel::JSON::XS') || + ($json->backend->isa('JSON::PP') && ($JSON::PP::Boolean::VERSION || $JSON::backportPP::Boolean::VERSION)) +) ? 1 : 0; + +is($json->encode([!1]), '[""]'); +if ($not_not_a_number_is_a_number) { +is($json->encode([!!2]), '[1]'); +} else { +is($json->encode([!!2]), '["1"]'); +} + +is($json->encode([ 'a' eq 'b' ]), '[""]'); +if ($not_not_a_number_is_a_number) { +is($json->encode([ 'a' eq 'a' ]), '[1]'); +} else { +is($json->encode([ 'a' eq 'a' ]), '["1"]'); +} + +is($json->encode([ ('a' eq 'b') + 1 ]), '[1]'); +is($json->encode([ ('a' eq 'a') + 1 ]), '[2]'); + +# discard overload hack for JSON::XS 3.0 boolean class +#ok(JSON::true eq 'true'); +#ok(JSON::true eq '1'); +ok(JSON::true == 1); +isa_ok(JSON::true, 'JSON::PP::Boolean'); +#isa_ok(JSON::true, 'JSON::Boolean'); + + + diff --git a/t/e03_bool2.t b/t/e03_bool2.t new file mode 100644 index 0000000..23ffc72 --- /dev/null +++ b/t/e03_bool2.t @@ -0,0 +1,43 @@ +use Test::More; + +BEGIN { plan tests => 16 }; + +BEGIN { $ENV{PERL_JSON_BACKEND} ||= "JSON::backportPP"; } +use JSON; + +is(to_json([JSON::true]), q|[true]|); +is(to_json([JSON::false]), q|[false]|); +is(to_json([JSON::null]), q|[null]|); + +my $jsontext = q|[true,false,null]|; +my $obj = from_json($jsontext); +#push @JSON::backportPP::Boolean::ISA, 'JSON::Boolean'; +isa_ok($obj->[0], 'JSON::PP::Boolean'); +isa_ok($obj->[1], 'JSON::PP::Boolean'); +ok(!defined $obj->[2], 'null is undef'); + +ok($obj->[0] == 1); +ok($obj->[0] != 0); +ok($obj->[1] == 0); +ok($obj->[1] != 1); +# discard overload hack for JSON::XS 3.0 boolean class +#ok($obj->[0] eq 'true', 'eq true'); +#ok($obj->[0] ne 'false', 'ne false'); +#ok($obj->[1] eq 'false', 'eq false'); +#ok($obj->[1] ne 'true', 'ne true'); + +ok($obj->[0] eq $obj->[0]); +ok($obj->[0] ne $obj->[1]); + +#ok(JSON::true eq 'true'); +#ok(JSON::true ne 'false'); +#ok(JSON::true ne 'null'); +#ok(JSON::false eq 'false'); +#ok(JSON::false ne 'true'); +#ok(JSON::false ne 'null'); +ok(!defined JSON::null); + +is(from_json('[true]' )->[0], JSON::true); +is(from_json('[false]')->[0], JSON::false); +is(from_json('[null]' )->[0], JSON::null); + diff --git a/t/e11_conv_blessed_univ.t b/t/e11_conv_blessed_univ.t new file mode 100644 index 0000000..e338f6d --- /dev/null +++ b/t/e11_conv_blessed_univ.t @@ -0,0 +1,52 @@ + +use strict; +use Test::More; +BEGIN { plan tests => 7 }; + +BEGIN { $ENV{PERL_JSON_BACKEND} ||= "JSON::backportPP"; } + +use JSON -convert_blessed_universally; + +ok( !MyTest->can('TO_JSON') ); +ok( MyTest2->can('TO_JSON') ); + +my $obj = MyTest->new( [ 1, 2, {foo => 'bar'} ] ); + +$obj->[3] = MyTest2->new( { a => 'b' } ); + +my $json = JSON->new->allow_blessed->convert_blessed; + +is( $json->encode( $obj ), '[1,2,{"foo":"bar"},"hoge"]' ); + +$json->convert_blessed(0); + +is( $json->encode( $obj ), 'null' ); + +$json->allow_blessed(0)->convert_blessed(1); + +is( $json->encode( $obj ), '[1,2,{"foo":"bar"},"hoge"]' ); + +SKIP: { + skip "only works with 5.18+", 1 if $] < 5.018; + ok( !MyTest->can('TO_JSON') ); +} +ok( MyTest2->can('TO_JSON') ); + +package MyTest; + +sub new { + bless $_[1], $_[0]; +} + + + +package MyTest2; + +sub new { + bless $_[1], $_[0]; +} + +sub TO_JSON { + "hoge"; +} + diff --git a/t/e90_misc.t b/t/e90_misc.t new file mode 100644 index 0000000..69b635a --- /dev/null +++ b/t/e90_misc.t @@ -0,0 +1,17 @@ +use strict; +use Test::More tests => 4; + +BEGIN { + $ENV{ PERL_JSON_BACKEND } ||= 'JSON::backportPP'; +} + +use JSON; + +# reported by https://rt.cpan.org/Public/Bug/Display.html?id=68359 + +eval { JSON->to_json( 5, { allow_nonref => 1 } ) }; +ok($@); + +is( q{"5"}, JSON::to_json( "5", { allow_nonref => 1 } ) ); +is( q{5}, JSON::to_json( 5, { allow_nonref => 1 } ) ); +is( q{"JSON"}, JSON::to_json( 'JSON', { allow_nonref => 1 } ) ); diff --git a/t/gh_28_json_test_suite.t b/t/gh_28_json_test_suite.t new file mode 100644 index 0000000..a8f7401 --- /dev/null +++ b/t/gh_28_json_test_suite.t @@ -0,0 +1,59 @@ +# the following test cases are taken from JSONTestSuite +# by Nicolas Seriot (https://github.com/nst/JSONTestSuite) + +use strict; +use Test::More; + +BEGIN { plan skip_all => 'this test is for Perl 5.8 or later' if $] < 5.008; } + +BEGIN { plan tests => 20 }; + +BEGIN { $ENV{PERL_JSON_BACKEND} = "JSON::backportPP"; } + +use JSON; + +my $DECODER = JSON->new->utf8->allow_nonref; + +# n_multidigit_number_then_00 +decode_should_fail(qq!123\x00!); + +# number_-01 +decode_should_fail(qq![-01]!); + +# number_neg_int_starting_with_zero +decode_should_fail(qq![-012]!); + +# n_object_trailing_comment +decode_should_fail(qq!{"a":"b"}/**/!); + +# n_object_trailing_comment_slash_open +decode_should_fail(qq!{"a":"b"}//!); + +# n_structure_null-byte-outside-sting +decode_should_fail(qq![\x00]!); + +# n_structure_object_with_comment +decode_should_fail(qq!{"a":/*comment*/"b"}!); + +# n_structure_whitespace_formfeed +decode_should_fail(qq![\0x0c]!); + +# y_string_utf16BE_no_BOM +decode_should_pass(qq!\x00[\x00"\x00\xE9\x00"\x00]!); + +# y_string_utf16LE_no_BOM +decode_should_pass(qq![\x00"\x00\xE9\x00"\x00]\x00!); + +sub decode_should_pass { + my $json = shift; + my $result = eval { $DECODER->decode($json); }; + ok !$@, $@ || ''; + ok defined $result; +} + +sub decode_should_fail { + my $json = shift; + my $result = eval { $DECODER->decode($json); }; + ok $@, $@ || ''; + ok !defined $result; +} diff --git a/t/gh_29_trailing_false_value.t b/t/gh_29_trailing_false_value.t new file mode 100644 index 0000000..5a42bb1 --- /dev/null +++ b/t/gh_29_trailing_false_value.t @@ -0,0 +1,13 @@ +use strict; +use Test::More; + +BEGIN { plan tests => 1 }; + +BEGIN { $ENV{PERL_JSON_BACKEND} ||= "JSON::backportPP"; } + +use JSON; + +SKIP: { skip "requires $JSON::BackendModule 2.90 or newer", 1 if $JSON::BackendModulePP and eval $JSON::BackendModulePP->VERSION < 2.90; + eval { JSON->new->decode('{}0') }; + ok $@; +} diff --git a/t/rt_116998_wrong_character_offset.t b/t/rt_116998_wrong_character_offset.t new file mode 100644 index 0000000..8b9c0c5 --- /dev/null +++ b/t/rt_116998_wrong_character_offset.t @@ -0,0 +1,22 @@ +use strict; +use Test::More; +BEGIN { plan tests => 4 }; +BEGIN { $ENV{PERL_JSON_BACKEND} ||= "JSON::backportPP"; } +use JSON; + +SKIP: { skip "requires $JSON::BackendModule 2.90 or newer", 1 if $JSON::BackendModulePP and eval $JSON::BackendModulePP->VERSION < 2.90; +eval { decode_json(qq({"foo":{"bar":42})) }; +like $@ => qr/offset 17/; # 16 +} + +eval { decode_json(qq(["foo",{"bar":42})) }; +like $@ => qr/offset 17/; + +SKIP: { skip "requires $JSON::BackendModule 2.90 or newer", 1 if $JSON::BackendModulePP and eval $JSON::BackendModulePP->VERSION < 2.90; +eval { decode_json(qq(["foo",{"bar":42}"])) }; +like $@ => qr/offset 17/; # 18 +} + +eval { decode_json(qq({"foo":{"bar":42}"})) }; +like $@ => qr/offset 17/; + diff --git a/t/rt_90071_incr_parse.t b/t/rt_90071_incr_parse.t new file mode 100644 index 0000000..c45de15 --- /dev/null +++ b/t/rt_90071_incr_parse.t @@ -0,0 +1,29 @@ +use strict; +use Test::More; +BEGIN { $ENV{PERL_JSON_BACKEND} ||= "JSON::backportPP"; } +use JSON; + +BEGIN { plan skip_all => "requires $JSON::BackendModule 2.90 or newer" if JSON->backend->is_pp and eval $JSON::BackendModule->VERSION < 2.90 } + +BEGIN { plan tests => 2 }; + +my $json = JSON->new; +my $kb = 'a' x 1024; +my $hash = { map { $_ => $kb } (1..40) }; +my $data = join ( '', $json->encode($hash), $json->encode($hash) ); +my $size = length($data); +# note "Total size: [$size]"; +my $offset = 0; +while ($size) { + # note "Bytes left [$size]"; + my $incr = substr($data, $offset, 4096); + my $bytes = length($incr); + $size -= $bytes; + $offset += $bytes; + if ($bytes) { + $json->incr_parse($incr); + } + while( my $obj = $json->incr_parse ) { + ok "Got JSON object"; + } +} diff --git a/t/x00_load.t b/t/x00_load.t new file mode 100644 index 0000000..f325c70 --- /dev/null +++ b/t/x00_load.t @@ -0,0 +1,15 @@ + +use strict; +use Test::More; +BEGIN { plan tests => 1 }; + +BEGIN { $ENV{PERL_JSON_BACKEND} ||= 1; } + +use JSON; + +SKIP: { + skip "can't use JSON::XS.", 1, unless( JSON->backend->is_xs ); + diag("load JSON::XS v." . JSON->backend->VERSION ); + ok(1, "load JSON::XS v." . JSON->backend->VERSION ); +} + diff --git a/t/x02_error.t b/t/x02_error.t new file mode 100644 index 0000000..02cb142 --- /dev/null +++ b/t/x02_error.t @@ -0,0 +1,56 @@ +use strict; +use Test::More; +BEGIN { plan tests => 31 }; + +BEGIN { $ENV{PERL_JSON_BACKEND} ||= 1; } + +local $^W; + +use utf8; +use JSON; + +SKIP: { + skip "can't use JSON::XS.", 31, unless( JSON->backend->is_xs ); + +eval { JSON->new->encode ([\-1]) }; ok $@ =~ /cannot encode reference/; +eval { JSON->new->encode ([\undef]) }; ok $@ =~ /cannot encode reference/; +eval { JSON->new->encode ([\2]) }; ok $@ =~ /cannot encode reference/; +eval { JSON->new->encode ([\{}]) }; ok $@ =~ /cannot encode reference/; +eval { JSON->new->encode ([\[]]) }; ok $@ =~ /cannot encode reference/; +eval { JSON->new->encode ([\\1]) }; ok $@ =~ /cannot encode reference/; + +eval { JSON->new->allow_nonref (1)->decode ('"\u1234\udc00"') }; ok $@ =~ /missing high /; +eval { JSON->new->allow_nonref->decode ('"\ud800"') }; ok $@ =~ /missing low /; +eval { JSON->new->allow_nonref (1)->decode ('"\ud800\u1234"') }; ok $@ =~ /surrogate pair /; + +eval { JSON->new->allow_nonref (0)->decode ('null') }; ok $@ =~ /allow_nonref/; +eval { JSON->new->allow_nonref (1)->decode ('+0') }; ok $@ =~ /malformed/; +eval { JSON->new->allow_nonref->decode ('.2') }; ok $@ =~ /malformed/; +eval { JSON->new->allow_nonref (1)->decode ('bare') }; ok $@ =~ /malformed/; +eval { JSON->new->allow_nonref->decode ('naughty') }; ok $@ =~ /null/; +eval { JSON->new->allow_nonref (1)->decode ('01') }; ok $@ =~ /leading zero/; +eval { JSON->new->allow_nonref->decode ('00') }; ok $@ =~ /leading zero/; +eval { JSON->new->allow_nonref (1)->decode ('-0.') }; ok $@ =~ /decimal point/; +eval { JSON->new->allow_nonref->decode ('-0e') }; ok $@ =~ /exp sign/; +eval { JSON->new->allow_nonref (1)->decode ('-e+1') }; ok $@ =~ /initial minus/; +eval { JSON->new->allow_nonref->decode ("\"\n\"") }; ok $@ =~ /invalid character/; +eval { JSON->new->allow_nonref (1)->decode ("\"\x01\"") }; ok $@ =~ /invalid character/; +eval { JSON->new->decode ('[5') }; ok $@ =~ /parsing array/; +eval { JSON->new->decode ('{"5"') }; ok $@ =~ /':' expected/; +eval { JSON->new->decode ('{"5":null') }; ok $@ =~ /parsing object/; + +eval { JSON->new->decode (undef) }; ok $@ =~ /malformed/; +eval { JSON->new->decode (\5) }; ok !!$@; # Can't coerce readonly +eval { JSON->new->decode ([]) }; ok $@ =~ /malformed/; +eval { JSON->new->decode (\*STDERR) }; ok $@ =~ /malformed/; +eval { JSON->new->decode (*STDERR) }; ok !!$@; # cannot coerce GLOB + +# differences between JSON::XS and JSON::PP + +eval { decode_json ("\"\xa0") }; ok $@ =~ /malformed.*character/; +eval { decode_json ("\"\xa0\"") }; ok $@ =~ /malformed.*character/; + +#eval { decode_json ("\"\xa0") }; ok $@ =~ /JSON text must be an object or array/; +#eval { decode_json ("\"\xa0\"") }; ok $@ =~ /JSON text must be an object or array/; + +} diff --git a/t/x12_blessed.t b/t/x12_blessed.t new file mode 100644 index 0000000..38edaf8 --- /dev/null +++ b/t/x12_blessed.t @@ -0,0 +1,54 @@ +use strict; +use Test::More; +BEGIN { plan tests => 16 }; + +BEGIN { $ENV{PERL_JSON_BACKEND} ||= 1; } + +use JSON; + +SKIP: { + skip "can't use JSON::XS.", 16, unless( JSON->backend->is_xs ); + +my $o1 = bless { a => 3 }, "XX"; +my $o2 = bless \(my $dummy = 1), "YY"; + +sub XX::TO_JSON { + {'__',""} +} + +my $js = JSON->new; + +eval { $js->encode ($o1) }; ok ($@ =~ /allow_blessed/); +eval { $js->encode ($o2) }; ok ($@ =~ /allow_blessed/); +$js->allow_blessed; +ok ($js->encode ($o1) eq "null"); +ok ($js->encode ($o2) eq "null"); +$js->convert_blessed; +ok ($js->encode ($o1) eq '{"__":""}'); + +ok ($js->encode ($o2) eq "null"); + +$js->filter_json_object (sub { 5 }); +$js->filter_json_single_key_object (a => sub { shift }); +$js->filter_json_single_key_object (b => sub { 7 }); + +ok ("ARRAY" eq ref $js->decode ("[]")); +ok (5 eq join ":", @{ $js->decode ('[{}]') }); +ok (6 eq join ":", @{ $js->decode ('[{"a":6}]') }); +ok (5 eq join ":", @{ $js->decode ('[{"a":4,"b":7}]') }); + +$js->filter_json_object; +ok (7 == $js->decode ('[{"a":4,"b":7}]')->[0]{b}); +ok (3 eq join ":", @{ $js->decode ('[{"a":3}]') }); + +$js->filter_json_object (sub { }); +ok (7 == $js->decode ('[{"a":4,"b":7}]')->[0]{b}); +ok (9 eq join ":", @{ $js->decode ('[{"a":9}]') }); + +$js->filter_json_single_key_object ("a"); +ok (4 == $js->decode ('[{"a":4}]')->[0]{a}); + +$js->filter_json_single_key_object (a => sub {}); +ok (4 == $js->decode ('[{"a":4}]')->[0]{a}); + +} diff --git a/t/x16_tied.t b/t/x16_tied.t new file mode 100644 index 0000000..7da67fb --- /dev/null +++ b/t/x16_tied.t @@ -0,0 +1,26 @@ +use strict; +use Test::More; +BEGIN { plan tests => 2 }; + +BEGIN { $ENV{PERL_JSON_BACKEND} ||= 1; } + +use JSON; +use Tie::Hash; +use Tie::Array; + +SKIP: { + skip "can't use JSON::XS.", 2, unless( JSON->backend->is_xs ); + +my $js = JSON->new; + +tie my %h, 'Tie::StdHash'; +%h = (a => 1); + +ok ($js->encode (\%h) eq '{"a":1}'); + +tie my @a, 'Tie::StdArray'; +@a = (1, 2); + +ok ($js->encode (\@a) eq '[1,2]'); + +} diff --git a/t/x17_strange_overload.t b/t/x17_strange_overload.t new file mode 100644 index 0000000..4405fc0 --- /dev/null +++ b/t/x17_strange_overload.t @@ -0,0 +1,22 @@ +use strict; +use Test::More; +BEGIN { plan tests => 2 }; + +BEGIN { $ENV{PERL_JSON_BACKEND} ||= 1; } + +SKIP: { + skip "for JSON::XS 3.x. cimpatible. Please see to Changes.", 2; + + eval q{ + use JSON::XS; + use JSON (); + }; + + skip "can't use JSON::XS.", 2, if $@; + skip "JSON::XS version < " . JSON->require_xs_version, 2 + if JSON::XS->VERSION < JSON->require_xs_version; + + is("" . JSON::XS::true(), 'true'); + is("" . JSON::true(), 'true'); +} + diff --git a/t/xe04_escape_slash.t b/t/xe04_escape_slash.t new file mode 100644 index 0000000..eeeaad1 --- /dev/null +++ b/t/xe04_escape_slash.t @@ -0,0 +1,22 @@ +use strict; +use Test::More; +BEGIN { plan tests => 3 }; + +BEGIN { $ENV{PERL_JSON_BACKEND} ||= 1; } + +use JSON -support_by_pp; + +SKIP: { + skip "can't use JSON::XS.", 3, unless( JSON->backend->is_xs ); + +my $json = new JSON; + + +is($json->escape_slash(0)->allow_nonref->encode("/"), '"/"'); +is($json->escape_slash(1)->allow_nonref->encode("/"), '"\/"'); +is($json->escape_slash(0)->allow_nonref->encode("/"), '"/"'); + + +} +__END__ + diff --git a/t/xe05_indent_length.t b/t/xe05_indent_length.t new file mode 100644 index 0000000..7493b28 --- /dev/null +++ b/t/xe05_indent_length.t @@ -0,0 +1,76 @@ +use strict; +use Test::More; +BEGIN { plan tests => 7 }; + +BEGIN { $ENV{PERL_JSON_BACKEND} ||= 1; } + +use JSON -support_by_pp; + +SKIP: { + skip "can't use JSON::XS.", 7, unless( JSON->backend->is_xs ); + +my $json = new JSON; + + +is($json->indent_length(2)->encode([1,{foo => 'bar'}, "1", "/"]), qq|[1,{"foo":"bar"},"1","/"]|); + +is($json->indent->encode([1,{foo => 'bar'}, "1", "/"]), qq|[ + 1, + { + "foo":"bar" + }, + "1", + "/" +] +|); + + +is($json->escape_slash(1)->pretty->indent_length(2)->encode([1,{foo => 'bar'}, "1", "/"]), qq|[ + 1, + { + "foo" : "bar" + }, + "1", + "\\/" +] +|); + + +is($json->escape_slash(1)->pretty->indent_length(3)->encode([1,{foo => 'bar'}, "1", "/"]), qq|[ + 1, + { + "foo" : "bar" + }, + "1", + "\\/" +] +|); + +is($json->escape_slash(1)->pretty->indent_length(15)->encode([1,{foo => 'bar'}, "1", "/"]), qq|[ + 1, + { + "foo" : "bar" + }, + "1", + "\\/" +] +|); + + +is($json->indent_length(0)->encode([1,{foo => 'bar'}, "1", "/"]), qq|[ +1, +{ +"foo" : "bar" +}, +"1", +"\\/" +] +|); + +is($json->indent(0)->space_before(0)->space_after(0)->escape_slash(0) + ->encode([1,{foo => 'bar'}, "1", "/"]), qq|[1,{"foo":"bar"},"1","/"]|); + + +} + + diff --git a/t/xe12_boolean.t b/t/xe12_boolean.t new file mode 100644 index 0000000..3513102 --- /dev/null +++ b/t/xe12_boolean.t @@ -0,0 +1,29 @@ + +use strict; +use Test::More; + +BEGIN { plan tests => 4 }; + +BEGIN { $ENV{PERL_JSON_BACKEND} ||= 1; } + +use JSON -support_by_pp; + +SKIP: { + skip "can't use JSON::XS.", 4, unless( JSON->backend->is_xs ); + +my $json = new JSON; +my $bool = $json->allow_nonref->decode('true'); + +# it's normal +isa_ok( $bool, 'JSON::PP::Boolean' ); +is( $json->encode([ JSON::true ]), '[true]' ); + +# make XS non support flag enable! +$bool = $json->allow_singlequote->decode('true'); + +isa_ok( $bool, 'JSON::PP::Boolean' ); +is( $json->encode([ JSON::true ]), '[true]' ); + +} + +__END__ diff --git a/t/xe19_xs_and_suportbypp.t b/t/xe19_xs_and_suportbypp.t new file mode 100644 index 0000000..d2467d5 --- /dev/null +++ b/t/xe19_xs_and_suportbypp.t @@ -0,0 +1,33 @@ +# https://rt.cpan.org/Public/Bug/Display.html?id=52847 + +use strict; +use Test::More; + +BEGIN { plan tests => 2 }; +BEGIN { $ENV{PERL_JSON_BACKEND} ||= 1; } + +use JSON -support_by_pp; + +SKIP: { + skip "can't use JSON::XS.", 2, unless( JSON->backend->is_xs ); + + my $json = JSON->new->allow_barekey; + +note explain test($json, q!{foo:"foo"}!); + for (1..2) { + is_deeply( test($json, q!{foo:"foo"}! ), {foo=>'foo'} ); + JSON->new->allow_singlequote(0); + } +} + + +sub test { + my ($coder, $str) = @_; + my $rv; + return $rv if eval { $rv = $coder->decode($str); 1 }; + chomp( my $e = $@ ); + return "died with \"$e\""; +}; + + + diff --git a/t/xe20_croak_message.t b/t/xe20_croak_message.t new file mode 100644 index 0000000..71621c7 --- /dev/null +++ b/t/xe20_croak_message.t @@ -0,0 +1,28 @@ +# https://rt.cpan.org/Public/Bug/Display.html?id=61708 + +use strict; +use Test::More; + +BEGIN { plan tests => 1 }; +BEGIN { $ENV{PERL_JSON_BACKEND} ||= 1; } + +use JSON -support_by_pp; +#use JSON; # currently it can't pass with -support_by_pp; + + +SKIP: { + skip "can't use JSON::XS.", 1, unless( JSON->backend->is_xs ); + + my $json = JSON->new; + + my $res = eval q{ $json->encode( undef ) }; + my $error = $@; + + # JSON::XS/JSON::PP 4.0 allow nonref by default + if ($json->get_allow_nonref) { + is $res => 'null'; + } else { + like( $error, qr/line 1\./ ); + } +} + diff --git a/t/xe21_is_pp.t b/t/xe21_is_pp.t new file mode 100644 index 0000000..4106b94 --- /dev/null +++ b/t/xe21_is_pp.t @@ -0,0 +1,28 @@ +use strict; +use Test::More; + +BEGIN { plan tests => 5 }; + +BEGIN { + $ENV{PERL_JSON_BACKEND} ||= 1; +} + +use JSON; + +my $json = JSON->new(); + +ok( $json->backend, 'backend is ' . $json->backend ); + +if ( $json->backend->is_xs ) { + ok (!JSON->is_pp(), 'JSON->is_pp()'); + ok ( JSON->is_xs(), 'JSON->is_xs()'); + ok (!$json->is_pp(), '$json->is_pp()'); + ok ( $json->is_xs(), '$json->is_xs()'); +} +else { + ok ( JSON->is_pp(), 'JSON->is_pp()'); + ok (!JSON->is_xs(), 'JSON->is_xs()'); + ok ( $json->is_pp(), '$json->is_pp()'); + ok (!$json->is_xs(), '$json->is_xs()'); +} + diff --git a/t/zero-mojibake.t b/t/zero-mojibake.t new file mode 100644 index 0000000..72c48f8 --- /dev/null +++ b/t/zero-mojibake.t @@ -0,0 +1,21 @@ +use strict; +use Test::More; +BEGIN { plan tests => 1 }; + +BEGIN { $ENV{PERL_JSON_BACKEND} ||= "JSON::backportPP"; } + +use JSON; + +my $json = JSON->new; + +my $input = q[ +{ + "dynamic_config" : 0, + "x_contributors" : [ + "大沢 åå®", + "Ãvar Arnfjörð" + ] +} +]; +eval { $json->decode($input) }; +is $@, '', 'decodes 0 with mojibake without error'; |