From c4356e5f64ce3e9176ceeb74d090456742f42e79 Mon Sep 17 00:00:00 2001 From: TizenOpenSource Date: Thu, 22 Feb 2024 14:39:59 +0900 Subject: [PATCH] Imported Upstream version 4.16 --- .travis.yml | 4 + Changes | 497 ++++ MANIFEST | 75 + META.json | 51 + META.yml | 27 + Makefile.PL | 36 + README | 25 + bin/json_pp | 237 ++ lib/JSON/PP.pm | 3142 ++++++++++++++++++++++++++ lib/JSON/PP/Boolean.pm | 43 + t/000_load.t | 13 + t/001_utf8.t | 32 + t/002_error.t | 56 + t/003_types.t | 72 + t/004_dwiw_encode.t | 70 + t/005_dwiw_decode.t | 91 + t/006_pc_pretty.t | 68 + t/007_pc_esc.t | 84 + t/008_pc_base.t | 99 + t/009_pc_extra_number.t | 39 + t/010_pc_keysort.t | 20 + t/011_pc_expo.t | 58 + t/012_blessed.t | 53 + t/013_limit.t | 33 + t/014_latin1.t | 19 + t/015_prefix.t | 20 + t/016_tied.t | 25 + t/017_relaxed.t | 25 + t/018_json_checker.t | 175 ++ t/019_incr.t | 108 + t/020_faihu.t | 30 + t/020_unknown.t | 46 + t/021_evans.t | 25 + t/022_comment_at_eof.t | 50 + t/052_object.t | 69 + t/099_binary.pl | 52 + t/099_binary00.t | 3 + t/099_binary01.t | 3 + t/099_binary02.t | 3 + t/099_binary03.t | 3 + t/099_binary04.t | 3 + t/099_binary05.t | 3 + t/099_binary06.t | 3 + t/099_binary07.t | 3 + t/099_binary08.t | 3 + t/099_binary09.t | 3 + t/099_binary10.t | 3 + t/099_binary11.t | 3 + t/099_binary12.t | 3 + t/099_binary13.t | 3 + t/099_binary14.t | 3 + t/099_binary15.t | 3 + t/104_sortby.t | 25 + t/105_esc_slash.t | 16 + t/106_allow_barekey.t | 20 + t/107_allow_singlequote.t | 21 + t/108_decode.t | 46 + t/109_encode.t | 44 + t/110_bignum.t | 51 + t/112_upgrade.t | 25 + t/113_overloaded_eq.t | 67 + t/114_decode_prefix.t | 28 + t/115_tie_ixhash.t | 47 + t/116_incr_parse_fixed.t | 24 + t/117_numbers.t | 25 + t/118_boolean_values.t | 81 + t/119_incr_parse_utf8.t | 75 + t/120_incr_parse_truncated.t | 218 ++ t/core_bools.t | 85 + t/gh_28_json_test_suite.t | 58 + t/gh_29_trailing_false_value.t | 14 + t/rt_116998_wrong_character_offset.t | 23 + t/rt_122270_old_xs_boolean.t | 33 + t/rt_90071_incr_parse.t | 30 + t/zero-mojibake.t | 22 + 75 files changed, 6695 insertions(+) create mode 100644 .travis.yml create mode 100644 Changes create mode 100644 MANIFEST create mode 100644 META.json create mode 100644 META.yml create mode 100644 Makefile.PL create mode 100644 README create mode 100644 bin/json_pp create mode 100644 lib/JSON/PP.pm create mode 100644 lib/JSON/PP/Boolean.pm create mode 100644 t/000_load.t create mode 100644 t/001_utf8.t create mode 100644 t/002_error.t create mode 100644 t/003_types.t create mode 100644 t/004_dwiw_encode.t create mode 100644 t/005_dwiw_decode.t create mode 100644 t/006_pc_pretty.t create mode 100644 t/007_pc_esc.t create mode 100644 t/008_pc_base.t create mode 100644 t/009_pc_extra_number.t create mode 100644 t/010_pc_keysort.t create mode 100644 t/011_pc_expo.t create mode 100644 t/012_blessed.t create mode 100644 t/013_limit.t create mode 100644 t/014_latin1.t create mode 100644 t/015_prefix.t create mode 100644 t/016_tied.t create mode 100644 t/017_relaxed.t create mode 100644 t/018_json_checker.t create mode 100644 t/019_incr.t create mode 100644 t/020_faihu.t create mode 100644 t/020_unknown.t create mode 100644 t/021_evans.t create mode 100644 t/022_comment_at_eof.t create mode 100644 t/052_object.t create mode 100644 t/099_binary.pl create mode 100644 t/099_binary00.t create mode 100644 t/099_binary01.t create mode 100644 t/099_binary02.t create mode 100644 t/099_binary03.t create mode 100644 t/099_binary04.t create mode 100644 t/099_binary05.t create mode 100644 t/099_binary06.t create mode 100644 t/099_binary07.t create mode 100644 t/099_binary08.t create mode 100644 t/099_binary09.t create mode 100644 t/099_binary10.t create mode 100644 t/099_binary11.t create mode 100644 t/099_binary12.t create mode 100644 t/099_binary13.t create mode 100644 t/099_binary14.t create mode 100644 t/099_binary15.t create mode 100644 t/104_sortby.t create mode 100644 t/105_esc_slash.t create mode 100644 t/106_allow_barekey.t create mode 100644 t/107_allow_singlequote.t create mode 100644 t/108_decode.t create mode 100644 t/109_encode.t create mode 100644 t/110_bignum.t create mode 100644 t/112_upgrade.t create mode 100644 t/113_overloaded_eq.t create mode 100644 t/114_decode_prefix.t create mode 100644 t/115_tie_ixhash.t create mode 100644 t/116_incr_parse_fixed.t create mode 100644 t/117_numbers.t create mode 100644 t/118_boolean_values.t create mode 100644 t/119_incr_parse_utf8.t create mode 100644 t/120_incr_parse_truncated.t create mode 100644 t/core_bools.t create mode 100644 t/gh_28_json_test_suite.t create mode 100644 t/gh_29_trailing_false_value.t create mode 100644 t/rt_116998_wrong_character_offset.t create mode 100644 t/rt_122270_old_xs_boolean.t create mode 100644 t/rt_90071_incr_parse.t create mode 100644 t/zero-mojibake.t diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000..cb96b2b --- /dev/null +++ b/.travis.yml @@ -0,0 +1,4 @@ +language: perl +perl: + - "5.8" + - "5.24" diff --git a/Changes b/Changes new file mode 100644 index 0000000..597c552 --- /dev/null +++ b/Changes @@ -0,0 +1,497 @@ +Revision history for Perl extension JSON::PP. + +4.16 2022-12-30 + - drop support for perls < 5.8 (GH#84, haarg++) + +4.15 2022-12-27 + - fix core bool test to not ignore errors (GH#82, haarg++) + +4.14 2022-12-26 + - updated manifest (GH#81, demerphq++) + +4.13 2022-12-26 + - Break up 099_binary.t into 16 pieces that can be tested in parallel (GH#80, demerphq++) + +4.12 2022-10-09 + - call unimport overload first to silence warnings (GH#76, haarg++) + +4.11 2022-07-31 + - restored cre boolean support (GH#73, #74, haarg++) + +4.10 2022-06-24 + - fix a regression of decode_error introduced at 4.08 (GH#75, reported by andk++) + - convert all tests to use Test::More (GH#70, haarg++) + +4.09 2022-05-22 + - reverted core boolean support for now (GH#72) + - incr_parse() Hangs on Certain Inputs (GH#67, DabeDotCom++) + - silence warnings about non-characters on older perls (GH#68, haarg++) + +4.08 2022-04-10 + - remove unneeded utf8::upgrade and downgrade (GH#59, FGasper++) + - core boolean support (GH#62, 63, haarg++) + - EBCDIC support (GH#64, khwilliamson++) + - shorten a test name (GH#65, khwilliamson) + +4.07 2021-12-17 + - fix incr_parse($unicode_str) bug (GH#56, DabeDotCom++) + +4.06 2021-01-24 + - fix return values of boolean_values for compatibility + (yahermann++) + +4.05 2020-07-09 + - no code changes + - modify tests for perl 7 (Nicolas R) + +4.04 2019-06-29 + - document indent_length option (GH#48) + +4.03 2019-06-19 + - (Encode::)decode json_pp input properly by default + (GH#47) + +4.02 2019-02-23 + - fix a test that breaks if perl is compiled with + -Dquadmath (RT-128589) + +4.01 2019-02-22 + - allow to pass indent_length to json_pp (GH#46) + +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 also enabled allow_nonref by default + + - implement allow_tags that was introduced by JSON::XS 3.0 + - add boolean_values that was introduced by JSON::XS 4.0 + - allow literal tags in strings in relaxed mode, as JSON::XS 3.02 does + - allow PERL_JSON_PP_USE_B environmental variable to restore + old number detection behavior for compatibility + - various doc updates + +2.97001 2017-12-21 + - tweak internal number detector to always considers a flagged + value as a string (GH#35, haarg++) + - clarify json_pp options (RT-123766; Dan Jacobson) + +2.97000 2017-11-21 + - fix is_bool to use blessed() instead of ref() (jwrightecs++) + - use 5 digit minor version number for a while to avoid confusion + (GH#33, dansut) + +2.96 2017-11-20 + - not to use newer Test::More features (RT-122421 for JSON) + +2.95 2017-11-20 + - json_pp now prints an encoded json string (RT#123653) + - fix is_bool to use ->isa("JSON::PP::Boolean"), instead + of UNIVERSAL::isa("JSON::PP::Boolean") (GH#34, aidy++) + +2.94 2017-05-29 + - fix a test to support perl 5.6 + +2.93 2017-05-15 + - fix packaging issue + +2.92 2017-05-15 + - production release + +2.91_04 2017-01-10 + - fixed isa tests for bignum + +2.91_03 2017-01-09 + - reworked documentation, based on the one for JSON::XS + - let json_pp utility to show the version of JSON::PP + - applied a patch to fix loading order of B module (pali++) + +2.91_02 2016-12-04 + - fixed not to fail tests under Perl 5.25.* (srezic++) + +2.91_01 2016-12-03 + - changed the number detection logic, patched by haarg + (experimental) + - merged PR from dagolden to correct 0 handling + - removed base.pm dependency (dolmen) + - fixed wrong character offset spotted by ilmari + - applied patches from Jarkko Hietaniemi to address VAX issues + - small doc fixes from bessarabov, gregoa, Chris Anderson + - applied a patch to remove . in @INC in json_pp (Tony Cook) + - removed $VAR1 from json_pp output, spotted by tokuhirom + - fixed an issue to ignore trailing 0 + - added Scalar::Util dependency for Perl 5.8+ + - fixed issues spotted by Nicolas Seriot's JSON Test Suite + including experimental UTF-16/32 support and backward + incompatible change of C style comment handling (now disabled + by default) + - moved the guts of JSON::PP::Boolean into lib/JSON/PP/Boolean.pm + and gave it a proper version + - refactored incremental parser to let it handle incomplete + JSON text properly + - imported and tweaked tests from JSON.pm + - minor code clean up + +2.27400 2016-04-23 + [JSON::PP] appleid and merged long term neglected patches & PRs. + thanks to charsbar + + - document patches + by AM909, leon[at]astray.com, dsteinbrunner, jwilk, alfiedotwtf + - modified Makefile.PL to set UNINST=1 if needed on old perls + by dagolden + - decode decimals to Perl's internal NV type + by dagolden + + see to https://github.com/makamaka/JSON-PP/commits/master + +2.27300 2014-10-06 + - fixed a problem about substr in perl 5.8.6 and below + many people report this issue and patched by haarg[at]haarg.org + +2.27203 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.27202 Wed Mar 13 15:41:22 2013 + - license in Makefile.PL was missing + +2.27201 Wed Mar 13 13:22:33 2013 + - occasionally failed in t/019_incr.t in Perl 5.17.6 or more + (because of hash iterator randomization) + reported and patched by demerphq + https://rt.cpan.org/Public/Bug/Display.html?id=83421 + +2.27200 Sun May 22 12:17:51 2011 + - fixed incr_parse decoding string more correctly (rt#68032 by LCONS) + +2.27105 Tue Mar 8 12:38:42 2011 + - removed t/900_pod.t from package because of author test + +2.27104 Thu Jan 20 19:06:25 2011 + - fixed a problem to convert overloaded objects (pointed by rt#64783) + - changed decoding methods object() and array() to pass a object. + +2.27103 Wed Dec 29 15:32:38 2010 + - added bin/json_pp - command line utility + +2.27102 Mon Dec 20 20:29:39 2010 + - modified JSON::PP::Boolean pod + +2.27101 Mon Dec 20 16:21:03 2010 + - renamed JSON::PPdev to JSON::PP + +2.27100 Sun Nov 28 02:02:49 2010 + - split away JSON distribution 2.27 (= JSON::PP 2.27008) + - renamed t/* files + +-------------------------------------------------------------------------- + old history +-------------------------------------------------------------------------- + +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 compatibility + 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 + referring 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 reference 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 compatibility 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 using 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..ed364d5 --- /dev/null +++ b/MANIFEST @@ -0,0 +1,75 @@ +.travis.yml +bin/json_pp +Changes +lib/JSON/PP.pm +lib/JSON/PP/Boolean.pm +Makefile.PL +MANIFEST This list of files +README +t/000_load.t +t/001_utf8.t +t/002_error.t +t/003_types.t +t/004_dwiw_encode.t +t/005_dwiw_decode.t +t/006_pc_pretty.t +t/007_pc_esc.t +t/008_pc_base.t +t/009_pc_extra_number.t +t/010_pc_keysort.t +t/011_pc_expo.t +t/012_blessed.t +t/013_limit.t +t/014_latin1.t +t/015_prefix.t +t/016_tied.t +t/017_relaxed.t +t/018_json_checker.t +t/019_incr.t +t/020_faihu.t +t/020_unknown.t +t/021_evans.t +t/022_comment_at_eof.t +t/052_object.t +t/099_binary.pl +t/099_binary00.t +t/099_binary01.t +t/099_binary02.t +t/099_binary03.t +t/099_binary04.t +t/099_binary05.t +t/099_binary06.t +t/099_binary07.t +t/099_binary08.t +t/099_binary09.t +t/099_binary10.t +t/099_binary11.t +t/099_binary12.t +t/099_binary13.t +t/099_binary14.t +t/099_binary15.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/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/119_incr_parse_utf8.t +t/120_incr_parse_truncated.t +t/core_bools.t +t/gh_28_json_test_suite.t +t/gh_29_trailing_false_value.t +t/rt_116998_wrong_character_offset.t +t/rt_122270_old_xs_boolean.t +t/rt_90071_incr_parse.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..7a0439c --- /dev/null +++ b/META.json @@ -0,0 +1,51 @@ +{ + "abstract" : "JSON::XS compatible pure-Perl module.", + "author" : [ + "Makamaka Hannyaharamitu, Emakamaka[at]cpan.orgE" + ], + "dynamic_config" : 1, + "generated_by" : "ExtUtils::MakeMaker version 7.34, CPAN::Meta::Converter version 2.150010", + "license" : [ + "perl_5" + ], + "meta-spec" : { + "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", + "version" : 2 + }, + "name" : "JSON-PP", + "no_index" : { + "directory" : [ + "t", + "inc" + ] + }, + "prereqs" : { + "build" : { + "requires" : { + "ExtUtils::MakeMaker" : "0" + } + }, + "configure" : { + "requires" : { + "ExtUtils::MakeMaker" : "0" + } + }, + "runtime" : { + "requires" : { + "Scalar::Util" : "1.08", + "Test::More" : "0" + } + } + }, + "release_status" : "stable", + "resources" : { + "bugtracker" : { + "web" : "https://github.com/makamaka/JSON-PP/issues" + }, + "repository" : { + "url" : "https://github.com/makamaka/JSON-PP" + } + }, + "version" : "4.16", + "x_serialization_backend" : "JSON::PP version 4.16" +} diff --git a/META.yml b/META.yml new file mode 100644 index 0000000..de65431 --- /dev/null +++ b/META.yml @@ -0,0 +1,27 @@ +--- +abstract: 'JSON::XS compatible pure-Perl module.' +author: + - 'Makamaka Hannyaharamitu, Emakamaka[at]cpan.orgE' +build_requires: + ExtUtils::MakeMaker: '0' +configure_requires: + ExtUtils::MakeMaker: '0' +dynamic_config: 1 +generated_by: 'ExtUtils::MakeMaker version 7.34, 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-PP +no_index: + directory: + - t + - inc +requires: + Scalar::Util: '1.08' + Test::More: '0' +resources: + bugtracker: https://github.com/makamaka/JSON-PP/issues + repository: https://github.com/makamaka/JSON-PP +version: '4.16' +x_serialization_backend: 'CPAN::Meta::YAML version 0.018' diff --git a/Makefile.PL b/Makefile.PL new file mode 100644 index 0000000..c329829 --- /dev/null +++ b/Makefile.PL @@ -0,0 +1,36 @@ +require 5.008; +use strict; +use ExtUtils::MakeMaker; + +use lib qw( ./lib ); + +# ensure old versions installed from bundled copy in ExtUtils::MakeMaker +# are removed when installing this; this will warn on old EU::MM but +# still works +my $needs_uninst = $] < 5.012 + && ! $ENV{PERL_NO_HIGHLANDER} + && ! ( $ENV{PERL_MM_OPT} && $ENV{PERL_MM_OPT} =~ /(?:INSTALL_BASE|PREFIX)/ ) + && ! grep { /INSTALL_BASE/ || /PREFIX/ } @ARGV; + +WriteMakefile( + 'NAME' => 'JSON::PP', + 'VERSION_FROM' => 'lib/JSON/PP.pm', # finds $VERSION + 'PREREQ_PM' => { + 'Test::More' => 0, + 'Scalar::Util' => '1.08' + }, + 'EXE_FILES' => [ 'bin/json_pp' ], + 'ABSTRACT_FROM' => 'lib/JSON/PP.pm', # retrieve abstract from module + 'AUTHOR' => 'Makamaka Hannyaharamitu, Emakamaka[at]cpan.orgE', + ( $ExtUtils::MakeMaker::VERSION >= 6.3002 ? ('LICENSE' => 'perl', ) : () ), + + ( $ExtUtils::MakeMaker::VERSION >= 6.46 ? ( + 'META_MERGE' => { + resources => { + repository => 'https://github.com/makamaka/JSON-PP', + bugtracker => 'https://github.com/makamaka/JSON-PP/issues', + }, + } ) : () + ), + ( $needs_uninst ? ( UNINST => 1 ) : () ), +); diff --git a/README b/README new file mode 100644 index 0000000..53e5593 --- /dev/null +++ b/README @@ -0,0 +1,25 @@ +JSON::PP +================= + +JSON::PP had been included in JSON distribution (CPAN module). +It was a perl core module in Perl 5.14. + +================= + +INSTALLATION + +To install this module type the following: + + perl Makefile.PL + make + make test + make install + +AUTHOR + Makamaka Hannyaharamitu, + +COPYRIGHT AND LICENSE + Copyright 2005-2016 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/bin/json_pp b/bin/json_pp new file mode 100644 index 0000000..72b9db7 --- /dev/null +++ b/bin/json_pp @@ -0,0 +1,237 @@ +#!/usr/bin/perl + +BEGIN { pop @INC if $INC[-1] eq '.' } +use strict; +use Getopt::Long; +use Encode (); + +use JSON::PP (); + +# imported from JSON-XS/bin/json_xs + +my %allow_json_opt = map { $_ => 1 } qw( + ascii latin1 utf8 pretty indent space_before space_after relaxed canonical allow_nonref + allow_singlequote allow_barekey allow_bignum loose escape_slash indent_length +); + + +GetOptions( + 'v' => \( my $opt_verbose ), + 'f=s' => \( my $opt_from = 'json' ), + 't=s' => \( my $opt_to = 'json' ), + 'json_opt=s' => \( my $json_opt = 'pretty' ), + 'V' => \( my $version ), +) or die "Usage: $0 [-V] [-f from_format] [-t to_format] [-json_opt options_to_json1[,options_to_json2[,...]]]\n"; + + +if ( $version ) { + print "$JSON::PP::VERSION\n"; + exit; +} + + +$json_opt = '' if $json_opt eq '-'; + +my %json_opt; +for my $opt (split /,/, $json_opt) { + my ($key, $value) = split /=/, $opt, 2; + $value = 1 unless defined $value; + die "'$_' is not a valid json option" unless $allow_json_opt{$key}; + $json_opt{$key} = $value; +} + +my %F = ( + 'json' => sub { + my $json = JSON::PP->new; + my $enc = + /^\x00\x00\x00/s ? "utf-32be" + : /^\x00.\x00/s ? "utf-16be" + : /^.\x00\x00\x00/s ? "utf-32le" + : /^.\x00.\x00/s ? "utf-16le" + : "utf-8"; + for my $key (keys %json_opt) { + next if $key eq 'utf8'; + $json->$key($json_opt{$key}); + } + $json->decode( Encode::decode($enc, $_) ); + }, + 'eval' => sub { + my $v = eval "no strict;\n#line 1 \"input\"\n$_"; + die "$@" if $@; + return $v; + }, +); + + +my %T = ( + 'null' => sub { "" }, + 'json' => sub { + my $json = JSON::PP->new->utf8; + for my $key (keys %json_opt) { + $json->$key($json_opt{$key}); + } + $json->canonical if $json_opt{pretty}; + $json->encode( $_ ); + }, + 'dumper' => sub { + require Data::Dumper; + local $Data::Dumper::Terse = 1; + local $Data::Dumper::Indent = 1; + local $Data::Dumper::Useqq = 1; + local $Data::Dumper::Quotekeys = 0; + local $Data::Dumper::Sortkeys = 1; + Data::Dumper::Dumper($_) + }, +); + + + +$F{$opt_from} + or die "$opt_from: not a valid fromformat\n"; + +$T{$opt_to} + or die "$opt_from: not a valid toformat\n"; + +{ + local $/; + binmode STDIN; + $_ = ; +} + +$_ = $F{$opt_from}->(); +$_ = $T{$opt_to}->(); + +print $_; + + +__END__ + +=pod + +=encoding utf8 + +=head1 NAME + +json_pp - JSON::PP command utility + +=head1 SYNOPSIS + + json_pp [-v] [-f from_format] [-t to_format] [-json_opt options_to_json1[,options_to_json2[,...]]] + +=head1 DESCRIPTION + +json_pp converts between some input and output formats (one of them is JSON). +This program was copied from L and modified. + +The default input format is json and the default output format is json with pretty option. + +=head1 OPTIONS + +=head2 -f + + -f from_format + +Reads a data in the given format from STDIN. + +Format types: + +=over + +=item json + +as JSON + +=item eval + +as Perl code + +=back + +=head2 -t + +Writes a data in the given format to STDOUT. + +=over + +=item null + +no action. + +=item json + +as JSON + +=item dumper + +as Data::Dumper + +=back + +=head2 -json_opt + +options to JSON::PP + +Acceptable options are: + + ascii latin1 utf8 pretty indent space_before space_after relaxed canonical allow_nonref + allow_singlequote allow_barekey allow_bignum loose escape_slash indent_length + +Multiple options must be separated by commas: + + Right: -json_opt pretty,canonical + + Wrong: -json_opt pretty -json_opt canonical + +=head2 -v + +Verbose option, but currently no action in fact. + +=head2 -V + +Prints version and exits. + + +=head1 EXAMPLES + + $ perl -e'print q|{"foo":"あい","bar":1234567890000000000000000}|' |\ + json_pp -f json -t dumper -json_opt pretty,utf8,allow_bignum + + $VAR1 = { + 'bar' => bless( { + 'value' => [ + '0000000', + '0000000', + '5678900', + '1234' + ], + 'sign' => '+' + }, 'Math::BigInt' ), + 'foo' => "\x{3042}\x{3044}" + }; + + $ perl -e'print q|{"foo":"あい","bar":1234567890000000000000000}|' |\ + json_pp -f json -t dumper -json_opt pretty + + $VAR1 = { + 'bar' => '1234567890000000000000000', + 'foo' => "\x{e3}\x{81}\x{82}\x{e3}\x{81}\x{84}" + }; + +=head1 SEE ALSO + +L, L + +=head1 AUTHOR + +Makamaka Hannyaharamitu, Emakamaka[at]cpan.orgE + + +=head1 COPYRIGHT AND LICENSE + +Copyright 2010 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/PP.pm b/lib/JSON/PP.pm new file mode 100644 index 0000000..fc8fcbc --- /dev/null +++ b/lib/JSON/PP.pm @@ -0,0 +1,3142 @@ +package JSON::PP; + +# JSON-2.0 + +use 5.008; +use strict; + +use Exporter (); +BEGIN { our @ISA = ('Exporter') } + +use overload (); +use JSON::PP::Boolean; + +use Carp (); +use Scalar::Util qw(blessed reftype refaddr); +#use Devel::Peek; + +our $VERSION = '4.16'; + +our @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 USE_B => $ENV{PERL_JSON_PP_USE_B} || 0; +use constant CORE_BOOL => defined &builtin::is_bool; + +my $invalid_char_re; + +BEGIN { + $invalid_char_re = "["; + for my $i (0 .. 0x01F, 0x22, 0x5c) { # '/' is ok + $invalid_char_re .= quotemeta chr utf8::unicode_to_native($i); + } + + $invalid_char_re = qr/$invalid_char_re]/; +} + +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 + ); + + 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; + if (CORE_BOOL) { + BEGIN { CORE_BOOL and warnings->unimport(qw(experimental::builtin)) } + if (builtin::is_bool($true) && builtin::is_bool($false) && $true && !$false) { + $self->{core_bools} = !!1; + } + else { + delete $self->{core_bools}; + } + } + } else { + delete $self->{false}; + delete $self->{true}; + delete $self->{core_bools}; + } + return $self; +} + +sub core_bools { + my $self = shift; + my $core_bools = defined $_[0] ? $_[0] : 1; + if ($core_bools) { + $self->{true} = !!1; + $self->{false} = !!0; + $self->{core_bools} = !!1; + } + else { + $self->{true} = $JSON::PP::true; + $self->{false} = $JSON::PP::false; + $self->{core_bools} = !!0; + } + return $self; +} + +sub get_core_bools { + my $self = shift; + return !!$self->{core_bools}; +} + +sub unblessed_bool { + my $self = shift; + return $self->core_bools(@_); +} + +sub get_unblessed_bool { + my $self = shift; + return $self->get_core_bools(@_); +} + +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 + + 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 ) ) { + 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) { + BEGIN { CORE_BOOL and warnings->unimport('experimental::builtin') } + if (CORE_BOOL && builtin::is_bool($value)) { + return $value ? 'true' : 'false'; + } + elsif (_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/(["\\\n\r\t\f\b])/$esc{$1}/g; + $arg =~ s/\//\\\//g if ($escape_slash); + + # On ASCII platforms, matches [\x00-\x08\x0b\x0e-\x1f] + $arg =~ s/([^\n\t\c?[:^cntrl:][:^ascii:]])/'\\u00' . unpack('H2', $1)/eg; + + if ($ascii) { + $arg = _encode_ascii($arg); + } + + if ($latin1) { + $arg = _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 { + chr($_) =~ /[[:ascii:]]/ ? + 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 + b => "\b", + t => "\t", + n => "\n", + f => "\f", + r => "\r", + '\\' => '\\', + '"' => '"', + '/' => '/', + ); + + 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::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 .= _decode_surrogates($utf16, $u) || next; + $utf16 = undef; + } + else { + if (defined $utf16) { + decode_error("surrogate pair expected"); + } + + my $hex = hex( $u ); + if ( chr $u =~ /[[:^ascii:]]/ ) { + $is_utf8 = 1; + $s .= _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 ( $ch =~ /[[:^ascii:]]/ ) { + 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 =~ $invalid_char_re) { # '/' ok + if (!$relaxed or $ch ne "\t") { + $at--; + decode_error(sprintf "invalid character 0x%X" + . " encountered while parsing JSON string", + ord $ch); + } + } + } + + $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 =~ /[\$\w[:^ascii:]]/){ + $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; + } + + # Compute how many bytes are in the longest legal official Unicode + # character + my $max_unicode_length = do { + no warnings 'utf8'; + chr 0x10FFFF; + }; + utf8::encode($max_unicode_length); + $max_unicode_length = length $max_unicode_length; + + sub is_valid_utf8 { + + # Returns undef (setting $utf8_len to 0) unless the next bytes in $text + # comprise a well-formed UTF-8 encoded character, in which case, + # return those bytes, setting $utf8_len to their count. + + my $start_point = substr($text, $at - 1); + + # Look no further than the maximum number of bytes in a single + # character + my $limit = $max_unicode_length; + $limit = length($start_point) if $limit > length($start_point); + + # Find the number of bytes comprising the first character in $text + # (without having to know the details of its internal representation). + # This loop will iterate just once on well-formed input. + while ($limit > 0) { # Until we succeed or exhaust the input + my $copy = substr($start_point, 0, $limit); + + # decode() will return true if all bytes are valid; false + # if any aren't. + if (utf8::decode($copy)) { + + # Is valid: get the first character, convert back to bytes, + # and return those bytes. + $copy = substr($copy, 0, 1); + utf8::encode($copy); + $utf8_len = length $copy; + return substr($start_point, 0, $utf8_len); + } + + # If it didn't work, it could be that there is a full legal character + # followed by a partial or malformed one. Narrow the window and + # try again. + $limit--; + } + + # Failed to find a legal UTF-8 character. + $utf8_len = 0; + return; + } + + + sub decode_error { + my $error = shift; + my $no_rep = shift; + my $str = defined $text ? substr($text, $at) : ''; + my $mess = ''; + my $type = 'U*'; + + for my $c ( unpack( $type, $str ) ) { # emulate pv_uni_display() ? + my $chr_c = chr($c); + $mess .= $chr_c eq '\\' ? '\\\\' + : $chr_c =~ /[[:print:]]/ ? $chr_c + : $chr_c eq '\a' ? '\a' + : $chr_c eq '\t' ? '\t' + : $chr_c eq '\n' ? '\n' + : $chr_c eq '\r' ? '\r' + : $chr_c eq '\f' ? '\f' + : 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; +} + +sub incr_parse { + local $Carp::CarpLevel = 1; + ( $_[0]->{_incr_parser} ||= JSON::PP::IncrParser->new )->incr_parse( @_ ); +} + + +sub incr_skip { + ( $_[0]->{_incr_parser} ||= JSON::PP::IncrParser->new )->incr_skip; +} + + +sub incr_reset { + ( $_[0]->{_incr_parser} ||= JSON::PP::IncrParser->new )->incr_reset; +} + +sub 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}; +} + + +############################### +# Utilities +# + +# 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 { + if (blessed $_[0]) { + return ( + $_[0]->isa("JSON::PP::Boolean") + or $_[0]->isa("Types::Serialiser::BooleanBase") + or $_[0]->isa("JSON::XS::Boolean") + ); + } + elsif (CORE_BOOL) { + BEGIN { CORE_BOOL and warnings->unimport('experimental::builtin') } + return builtin::is_bool($_[0]); + } + return !!0; +} + +sub true { $JSON::PP::true } +sub false { $JSON::PP::false } +sub null { undef; } + +############################### + +package 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; + +our $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 ) { + $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; + } + } + + unless ( $coder->get_utf8 ) { + utf8::decode( $self->{incr_text} ); + } + + 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) > ord " " ) { + 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 ) { + last INCR_PARSE if $p >= $len && $self->{incr_nest}; + 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 ) { + last INCR_PARSE if $p >= $len && $self->{incr_nest}; + 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 =~ /^[\t\n\r ]$/) { + 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 DESCRIPTION + +JSON::PP is a pure perl JSON decoder/encoder, and (almost) compatible to much +faster L written by Marc Lehmann in C. JSON::PP works as +a fallback module when you use L 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, which is derived from L 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 +and C 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: 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 and C in Perl strings. + +On perl 5.36 and above, will also return true when given one of perl's +standard boolean values, such as the result of a comparison. + +See L, 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 +(with the exception of C, which defaults to I 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 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 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 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 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 method +will not be affected in any way by this flag, as C by default +expects Unicode, which is a strict superset of latin1. + +If C<$enable> is false, then the C method will not escape Unicode +characters unless required by the JSON syntax or other flags. + +See also the section I 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 method will encode +the JSON result into UTF-8, as required by many protocols, while the +C 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 method will return the JSON +string as a (non-encoded) Unicode string, while C 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 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, C and +C (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 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. + +This setting has no effect when decoding JSON texts. + +The default indent space length is three. +You can use C 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 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 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. + +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 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 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 will accept some +extensions to normal JSON syntax (see below). C will not be +affected in anyway. I. 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 will only accept +valid JSON texts. + +Currently accepted extensions are: + +=over 4 + +=item * list items can have an end-comma + +JSON I 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", + "HelloWorld", # literal 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 method will output JSON objects +by sorting their keys. This is adding a comparatively high overhead. + +If C<$enable> is false, then the C 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 method can convert a +non-reference into its corresponding string, number or null JSON value, +which is an extension to RFC4627. Likewise, C will accept those JSON +values instead of croaking. + +If C<$enable> is false, then the C method will croak if it isn't +passed an arrayref or hashref, as JSON texts must either be an object +or array. Likewise, C will croak if given something that is not a +JSON object or array. + +Example, encode a Perl scalar as JSON value without enabled C, +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 will I throw an +exception when it encounters values it cannot represent in JSON (for +example, filehandles) but instead will encode a JSON C value. Note +that blessed objects are not included here and are handled separately by +c. + +If C<$enable> is false (the default), then C will throw an +exception when it encounters anything it cannot encode as JSON. + +This option does not affect C 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 for details. + +If C<$enable> is true (or missing), then the C method will not +barf when it encounters a blessed reference that it cannot convert +otherwise. Instead, a JSON C value is encoded instead of the object. + +If C<$enable> is false (the default), then C will throw an +exception when it encounters a blessed object that it cannot convert +otherwise. + +This setting has no effect on C. + +=head2 convert_blessed + + $json = $json->convert_blessed([$enable]) + + $enabled = $json->get_convert_blessed + +See L for details. + +If C<$enable> is true (or missing), then C, upon encountering a +blessed object, will check for the availability of the C 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 method may safely call die if it wants. If C +returns other blessed objects, those will be handled in the same +way. C must take care of not causing an endless recursion cycle +(== crash) in this case. The name of C 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 +function or method. + +If C<$enable> is false (the default), then C will not consider +this type of conversion. + +This setting has no effect on C. + +=head2 allow_tags + + $json = $json->allow_tags([$enable]) + + $enabled = $json->get_allow_tags + +See L for details. + +If C<$enable> is true (or missing), then C, upon encountering a +blessed object, will check for the availability of the C 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 to parse such tagged JSON values and deserialise +them via a call to the C method. + +If C<$enable> is false (the default), then C will not consider +this type of conversion, and tagged JSON values will cause a parse error +in C, 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 will be decoded as a copy of C<$false>, and JSON +C 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. You can set incompatible +boolean objects (like L), but when you C a data structure +with such boolean objects, you still need to enable C +(and add a C method if necessary). + +Calling this method without any arguments will reset the booleans +to their default values. + +C will return both C<$false> and C<$true> values, or +the empty list when they are set to the default. + +=head2 core_bools + + $json->core_bools([$enable]); + +If C<$enable> is true (or missing), then C, will produce standard +perl boolean values. Equivalent to calling: + + $json->boolean_values(!!1, !!0) + +C will return true if this has been set. On perl 5.36, it will +also return true if the boolean values have been set to perl's core booleans +using the C method. + +The methods C and C are provided as aliases +for compatibility with L. + +=head2 filter_json_object + + $json = $json->filter_json_object([$coderef]) + +When C<$coderef> is specified, it will be called from C 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 C, 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 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, 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, 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 but the empty list), +the callback from C 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 +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__" => } >> +into the corresponding C<< $WIDGET{} >> 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 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 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 +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 (yet). + +If no argument is given, the limit check will be deactivated (same as when +C<0> is specified). + +See L 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: 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 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, 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 will accept +invalid JSON texts that contain strings that begin and end with +single quotation marks. C will not be affected in any way. +I. 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 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 will accept +invalid JSON texts that contain JSON objects whose names don't +begin and end with quotation marks. C will not be affected +in any way. I. 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 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 will convert +big integers Perl cannot handle as integer into L +objects and convert floating numbers into L +objects. C will convert C and C +objects into JSON numbers. + + $json->allow_nonref->allow_bignum; + $bigfloat = $json->decode('2.000000000000000000000000001'); + print $json->encode($bigfloat); + # => 2.000000000000000000000000001 + +See also L. + +=head2 loose + + $json = $json->loose([$enable]) + $enabled = $json->get_loose + +If C<$enable> is true (or missing), then C will accept +invalid JSON texts that contain unescaped [\x00-\x1f\x22\x5c] +characters. C will not be affected in any way. +I. 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 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 will explicitly +escape I (solidus; C) characters to reduce the risk of +XSS (cross site scripting) that may be caused by C<< >> +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 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 or C. + +JSON::XS indents with three spaces when you C (if requested +by C or C), 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) 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, enable C 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, +then the argument will be passed to Perl's C built-in function. + +As the sorting is done in the JSON::PP scope, you usually need to +prepend C to the subroutine name, and the special variables +C<$a> and C<$b> used in the subrontine used by C 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 affects all the plain hashes in the data structure. +If you need finer control, C necessary hashes with a module that +implements ordered hash (such as L and L). +C and C don't affect the key order in Cd +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 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) 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 JSON object. If that is successful, it will return this +object, otherwise it will return C. If there is a parse error, +this method will croak just as C would do (one can then use +C 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 works when a preceding call to +C in I 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 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 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 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 refers to the Perl interpreter, while uppercase I +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 is enabled, big integer values and any numeric +values will be converted into L and L +objects respectively, without becoming string scalars or losing +precision. + +=item true, false + +These JSON atoms become C and C, +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 function. + +=item null + +A JSON null atom becomes C in Perl. + +=item shell-style comments (C<< # I >>) + +As a nonstandard extension to the JSON syntax that is enabled by the +C 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)I >>). + +Another nonstandard extension to the JSON syntax, enabled with the +C setting, are tagged values. In this implementation, the +I must be a perl package/class name encoded as a JSON string, and the +I must be a JSON array encoding optional constructor arguments. + +See L, 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 flag and/or I 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 and C atoms in JSON. You can +also use C and C 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 +allows various ways of handling objects. See L, +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 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 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 method +(or C 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 or C, 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 encounters a Perl object depends on the +C, C, C and C +settings, which are used in this order: + +=over 4 + +=item 1. C is enabled and the object has a C method. + +In this case, C creates a tagged JSON value, using a nonstandard +extension to the JSON syntax. + +This works by invoking the C method on the object, with the first +argument being the object to serialise, and the second argument being the +constant string C to distinguish it from other serialisers. + +The C 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 C method might use the +objects C and C members to encode the object: + + sub My::Object::FREEZE { + my ($self, $serialiser) = @_; + + ($self->{type}, $self->{id}) + } + +=item 2. C is enabled and the object has a C method. + +In this case, the C 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 method will convert all L +objects to JSON strings when serialised. The fact that these values +originally were L objects is lost. + + sub URI::TO_JSON { + my ($uri) = @_; + $uri->as_string + } + +=item 3. C is enabled and the object is a C or C. + +The object will be serialised as a JSON number value. + +=item 4. C 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 throws an exception. + +=back + +=head3 DESERIALISATION + +For deserialisation there are only two cases to consider: either +nonstandard tagging was used, in which case C decides, +or objects cannot be automatically be deserialised, in which +case you can use postprocessing or the C or +C 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 is disabled, a parse +error will result (as if tagged values were not part of the grammar). + +If C is enabled, C will look up the C 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 method is invoked with the classname as first +argument, the constant string C as second argument, and all the +values from the JSON array (the values originally returned by the +C 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 setting to +make that work in all cases, so better return an actual blessed reference. + +As an example, let's implement a C function that regenerates the +C from the C 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, C and C. There seems to be +some confusion on what these do, so here is a short comparison: + +C controls whether the JSON text created by C (and expected +by C) is UTF-8 encoded or not, while C and C only +control whether C 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 and C, 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 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 encodings at +the same time, which can be confusing. + +=over 4 + +=item C flag disabled + +When C is disabled (the default), then C/C 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 flag enabled + +If the C-flag is enabled, C/C 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 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 or C flags enabled + +With C (or C) enabled, C will escape characters +with ordinal values > 255 (> 127 with C) and encode the remaining +characters as specified by the C flag. + +If C 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 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 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 being +a subset of Unicode), while ASCII is. + +Surprisingly, C will ignore these flags and so treat all input +values as governed by the C 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 nor C are incompatible with the C flag - +they only govern when the JSON output engine escapes a character or not. + +The main use for C is to relatively efficiently store binary data +as JSON, at the expense of breaking compatibility with most JSON decoders. + +The main use for C 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 + +L + +As for new features and requests to change common behaviors, please +ask the author of JSON::XS (Marc Lehmann, Eschmorp[at]schmorp.deE) +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, which is smaller and +written in a much cleaner way than this module. + +=head1 SEE ALSO + +The F command line utility for quick experiments. + +L, L, and L for faster alternatives. +L and L for easy migration. + +L and L for older perl users. + +RFC4627 (L) + +RFC7159 (L) + +RFC8259 (L) + +=head1 AUTHOR + +Makamaka Hannyaharamitu, Emakamaka[at]cpan.orgE + +=head1 CURRENT MAINTAINER + +Kenichi Ishigaki, Eishigaki[at]cpan.orgE + +=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/PP/Boolean.pm b/lib/JSON/PP/Boolean.pm new file mode 100644 index 0000000..146446e --- /dev/null +++ b/lib/JSON/PP/Boolean.pm @@ -0,0 +1,43 @@ +package JSON::PP::Boolean; + +use strict; +use warnings; +use overload (); +overload::unimport('overload', qw(0+ ++ -- fallback)); +overload::import('overload', + "0+" => sub { ${$_[0]} }, + "++" => sub { $_[0] = ${$_[0]} + 1 }, + "--" => sub { $_[0] = ${$_[0]} - 1 }, + fallback => 1, +); + +our $VERSION = '4.16'; + +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 for more info about this class. + +=head1 AUTHOR + +This idea is from L written by Marc Lehmann + +=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/t/000_load.t b/t/000_load.t new file mode 100644 index 0000000..112b47b --- /dev/null +++ b/t/000_load.t @@ -0,0 +1,13 @@ +# copied over from JSON::XS and modified to use JSON::PP + +use strict; +use warnings; + +my $loaded; +BEGIN { $| = 1; print "1..1\n"; } +END {print "not ok 1\n" unless $loaded;} +BEGIN { $ENV{PERL_JSON_BACKEND} = 0; } + +use JSON::PP; +$loaded = 1; +print "ok 1\n"; diff --git a/t/001_utf8.t b/t/001_utf8.t new file mode 100644 index 0000000..4044e44 --- /dev/null +++ b/t/001_utf8.t @@ -0,0 +1,32 @@ +# copied over from JSON::XS and modified to use JSON::PP + +use strict; +use warnings; +use Test::More; +BEGIN { plan tests => 9 }; + +BEGIN { $ENV{PERL_JSON_BACKEND} = 0; } + +use utf8; +use JSON::PP; + +my $pilcrow_utf8 = (ord "^" == 0x5E) ? "\xc2\xb6" # 8859-1 + : (ord "^" == 0x5F) ? "\x80\x65" # CP 1024 + : "\x78\x64"; # assume CP 037 +is (JSON::PP->new->allow_nonref (1)->utf8 (1)->encode ("¶"), "\"$pilcrow_utf8\""); +is (JSON::PP->new->allow_nonref (1)->encode ("¶"), "\"¶\""); +is (JSON::PP->new->allow_nonref (1)->ascii (1)->utf8 (1)->encode (chr 0x8000), '"\u8000"'); +is (JSON::PP->new->allow_nonref (1)->ascii (1)->utf8 (1)->pretty (1)->encode (chr 0x10402), "\"\\ud801\\udc02\"\n"); + +eval { JSON::PP->new->allow_nonref (1)->utf8 (1)->decode ('"¶"') }; +ok $@ =~ /malformed UTF-8/; + +is (JSON::PP->new->allow_nonref (1)->decode ('"¶"'), "¶"); +is (JSON::PP->new->allow_nonref (1)->decode ('"\u00b6"'), "¶"); +is (JSON::PP->new->allow_nonref (1)->decode ('"\ud801\udc02' . "\x{10204}\""), "\x{10402}\x{10204}"); + +my $controls = (ord "^" == 0x5E) ? "\012\\\015\011\014\010" + : (ord "^" == 0x5F) ? "\025\\\015\005\014\026" # CP 1024 + : "\045\\\015\005\014\026"; # assume CP 037 +is (JSON::PP->new->allow_nonref (1)->decode ('"\"\n\\\\\r\t\f\b"'), "\"$controls"); + diff --git a/t/002_error.t b/t/002_error.t new file mode 100644 index 0000000..ae7b773 --- /dev/null +++ b/t/002_error.t @@ -0,0 +1,56 @@ +# copied over from JSON::XS and modified to use JSON::PP + +use strict; +use warnings; +use Test::More; +BEGIN { plan tests => 35 }; + +BEGIN { $ENV{PERL_JSON_BACKEND} = 0; } + +use utf8; +use JSON::PP; +no warnings; + + +eval { JSON::PP->new->encode ([\-1]) }; ok $@ =~ /cannot encode reference/; +eval { JSON::PP->new->encode ([\undef]) }; ok $@ =~ /cannot encode reference/; +eval { JSON::PP->new->encode ([\2]) }; ok $@ =~ /cannot encode reference/; +eval { JSON::PP->new->encode ([\{}]) }; ok $@ =~ /cannot encode reference/; +eval { JSON::PP->new->encode ([\[]]) }; ok $@ =~ /cannot encode reference/; +eval { JSON::PP->new->encode ([\\1]) }; ok $@ =~ /cannot encode reference/; + +eval { JSON::PP->new->allow_nonref (1)->decode ('"\u1234\udc00"') }; ok $@ =~ /missing high /; +eval { JSON::PP->new->allow_nonref->decode ('"\ud800"') }; ok $@ =~ /missing low /; +eval { JSON::PP->new->allow_nonref (1)->decode ('"\ud800\u1234"') }; ok $@ =~ /surrogate pair /; + +eval { JSON::PP->new->allow_nonref (0)->decode ('null') }; ok $@ =~ /allow_nonref/; +eval { JSON::PP->new->allow_nonref (1)->decode ('+0') }; ok $@ =~ /malformed/; +eval { JSON::PP->new->allow_nonref->decode ('.2') }; ok $@ =~ /malformed/; +eval { JSON::PP->new->allow_nonref (1)->decode ('bare') }; ok $@ =~ /malformed/; +eval { JSON::PP->new->allow_nonref->decode ('naughty') }; ok $@ =~ /null/; +eval { JSON::PP->new->allow_nonref (1)->decode ('01') }; ok $@ =~ /leading zero/; +eval { JSON::PP->new->allow_nonref->decode ('00') }; ok $@ =~ /leading zero/; +eval { JSON::PP->new->allow_nonref (1)->decode ('-0.') }; ok $@ =~ /decimal point/; +eval { JSON::PP->new->allow_nonref->decode ('-0e') }; ok $@ =~ /exp sign/; +eval { JSON::PP->new->allow_nonref (1)->decode ('-e+1') }; ok $@ =~ /initial minus/; +eval { JSON::PP->new->allow_nonref->decode ("\"\n\"") }; ok $@ =~ /invalid character/; +eval { JSON::PP->new->allow_nonref (1)->decode ("\"\x01\"") }; ok $@ =~ /invalid character/; +eval { JSON::PP->new->decode ('[5') }; ok $@ =~ /parsing array/; +eval { JSON::PP->new->decode ('{"5"') }; ok $@ =~ /':' expected/; +eval { JSON::PP->new->decode ('{"5":null') }; ok $@ =~ /parsing object/; + +eval { JSON::PP->new->decode (undef) }; ok $@ =~ /malformed/; +eval { JSON::PP->new->decode (\5) }; ok !!$@; # Can't coerce readonly +eval { JSON::PP->new->decode ([]) }; ok $@ =~ /malformed/; +eval { JSON::PP->new->decode (\*STDERR) }; ok $@ =~ /malformed/; +eval { JSON::PP->new->decode (*STDERR) }; ok !!$@; # cannot coerce GLOB + +eval { decode_json ("\"\xa0") }; ok $@ =~ /malformed.*character/; +eval { decode_json ("\"\xa0\"") }; ok $@ =~ /malformed.*character/; +{ #SKIP_UNLESS_XS4_COMPAT 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/003_types.t b/t/003_types.t new file mode 100644 index 0000000..feaeeb2 --- /dev/null +++ b/t/003_types.t @@ -0,0 +1,72 @@ +# copied over from JSON::XS and modified to use JSON::PP + +use strict; +use warnings; +use Test::More; +BEGIN { plan tests => 78 + 2 }; + +BEGIN { $ENV{PERL_JSON_BACKEND} = 0; } + +use utf8; +use JSON::PP; + + +ok (!defined JSON::PP->new->allow_nonref (1)->decode ('null')); +ok (JSON::PP->new->allow_nonref (1)->decode ('true') == 1); +ok (JSON::PP->new->allow_nonref (1)->decode ('false') == 0); + +my $true = JSON::PP->new->allow_nonref (1)->decode ('true'); +ok ($true eq 1); +ok (JSON::PP::is_bool $true); +my $false = JSON::PP->new->allow_nonref (1)->decode ('false'); +ok ($false == !$true); +ok (JSON::PP::is_bool $false); +ok (++$false == 1); +ok (!JSON::PP::is_bool $false); +ok (!JSON::PP::is_bool "JSON::PP::Boolean"); +ok (!JSON::PP::is_bool {}); # GH-34 + +ok (JSON::PP->new->allow_nonref (1)->decode ('5') == 5); +ok (JSON::PP->new->allow_nonref (1)->decode ('-5') == -5); +ok (JSON::PP->new->allow_nonref (1)->decode ('5e1') == 50); +ok (JSON::PP->new->allow_nonref (1)->decode ('-333e+0') == -333); +ok (JSON::PP->new->allow_nonref (1)->decode ('2.5') == 2.5); + +ok (JSON::PP->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::PP->new->canonical (1)->encode (decode_json '{ "1" : 2, "3" : 4 }')); +ok ('{"1":2,"3":1.2}' eq JSON::PP->new->canonical (1)->encode (decode_json '{ "1" : 2, "3" : 1.2 }')); + +ok ('[true]' eq encode_json [JSON::PP::true]); +ok ('[false]' eq encode_json [JSON::PP::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::PP::true]); +ok ('[false]' eq encode_json [JSON::PP::false]); + +SKIP: { + skip "core booleans not supported", 2 + unless JSON::PP->can("CORE_BOOL") && JSON::PP::CORE_BOOL(); + + ok ('[true]' eq encode_json [!!1]); + ok ('[false]' eq encode_json [!!0]); +} + +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/004_dwiw_encode.t b/t/004_dwiw_encode.t new file mode 100644 index 0000000..f413e87 --- /dev/null +++ b/t/004_dwiw_encode.t @@ -0,0 +1,70 @@ +# copied over from JSON::XS and modified to use JSON::PP + +# copied over from JSON::DWIW and modified to use JSON::PP + +# Creation date: 2007-02-20 19:51:06 +# Authors: don + +use strict; +use warnings; +use Test::More tests => 5; + +# main +{ + BEGIN { $ENV{PERL_JSON_BACKEND} = 0; } + +use JSON::PP; + + 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::PP->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/005_dwiw_decode.t b/t/005_dwiw_decode.t new file mode 100644 index 0000000..ab195ad --- /dev/null +++ b/t/005_dwiw_decode.t @@ -0,0 +1,91 @@ +# copied over from JSON::XS and modified to use JSON::PP + +# copied over from JSON::DWIW and modified to use JSON::PP + +# Creation date: 2007-02-20 21:54:09 +# Authors: don + +use strict; +use warnings; +use Test::More tests => 7; + +# main +{ + BEGIN { $ENV{PERL_JSON_BACKEND} = 0; } + +use JSON::PP; + + my $json_str = '{"var1":"val1","var2":["first_element",{"sub_element":"sub_val","sub_element2":"sub_val2"}],"var3":"val3"}'; + + my $json_obj = JSON::PP->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/006_pc_pretty.t b/t/006_pc_pretty.t new file mode 100644 index 0000000..c8a5a0a --- /dev/null +++ b/t/006_pc_pretty.t @@ -0,0 +1,68 @@ +# copied over from JSON::PC and modified to use JSON::PP +# copied over from JSON::XS and modified to use JSON::PP + +use strict; +use warnings; +use Test::More; +BEGIN { plan tests => 9 }; + +BEGIN { $ENV{PERL_JSON_BACKEND} = 0; } + +use JSON::PP; + +my ($js,$obj,$json); +my $pc = JSON::PP->new; + +$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/007_pc_esc.t b/t/007_pc_esc.t new file mode 100644 index 0000000..32fe808 --- /dev/null +++ b/t/007_pc_esc.t @@ -0,0 +1,84 @@ +# +# このファイルのエンコーディングはUTF-8 +# + +# copied over from JSON::PC and modified to use JSON::PP +# copied over from JSON::XS and modified to use JSON::PP + +use Test::More; +use strict; +use warnings; +use utf8; +BEGIN { plan tests => 17 }; +BEGIN { $ENV{PERL_JSON_BACKEND} = 0; } + +use JSON::PP; + +######################### +my ($js,$obj,$str); + +my $pc = JSON::PP->new; + +$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/008_pc_base.t b/t/008_pc_base.t new file mode 100644 index 0000000..e717bae --- /dev/null +++ b/t/008_pc_base.t @@ -0,0 +1,99 @@ +use Test::More; + +# copied over from JSON::PC and modified to use JSON::PP +# copied over from JSON::XS and modified to use JSON::PP + +use strict; +use warnings; +BEGIN { plan tests => 20 }; +BEGIN { $ENV{PERL_JSON_BACKEND} = 0; } + +use JSON::PP; + +my ($js,$obj); + +my $pc = JSON::PP->new; + +$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), (ord("A") == 65) ? '["\\u001b"]' : '["\\u0027"]'); +$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/009_pc_extra_number.t b/t/009_pc_extra_number.t new file mode 100644 index 0000000..d062f03 --- /dev/null +++ b/t/009_pc_extra_number.t @@ -0,0 +1,39 @@ +# copied over from JSON::PC and modified to use JSON::PP +# copied over from JSON::XS and modified to use JSON::PP + +use Test::More; +use strict; +use warnings; +BEGIN { plan tests => 6 }; +BEGIN { $ENV{PERL_JSON_BACKEND} = 0; } + +use JSON::PP; +use utf8; + +######################### +my ($js,$obj); +my $pc = JSON::PP->new; + +$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/010_pc_keysort.t b/t/010_pc_keysort.t new file mode 100644 index 0000000..2dba569 --- /dev/null +++ b/t/010_pc_keysort.t @@ -0,0 +1,20 @@ +# copied over from JSON::PC and modified to use JSON::PP +# copied over from JSON::XS and modified to use JSON::PP + +use Test::More; +use strict; +use warnings; +BEGIN { plan tests => 1 }; +BEGIN { $ENV{PERL_JSON_BACKEND} = 0; } + +use JSON::PP; +######################### + +my ($js,$obj); +my $pc = JSON::PP->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/011_pc_expo.t b/t/011_pc_expo.t new file mode 100644 index 0000000..443b0d8 --- /dev/null +++ b/t/011_pc_expo.t @@ -0,0 +1,58 @@ +# copied over from JSON::PC and modified to use JSON::PP +# copied over from JSON::XS and modified to use JSON::PP + +use Test::More; +use strict; +use warnings; +BEGIN { plan tests => 8 + 2 }; +BEGIN { $ENV{PERL_JSON_BACKEND} = 0; } + +use JSON::PP; + +######################### +my ($js,$obj); +my $pc = JSON::PP->new; + +$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_IF_CPANEL +$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/012_blessed.t b/t/012_blessed.t new file mode 100644 index 0000000..51f8558 --- /dev/null +++ b/t/012_blessed.t @@ -0,0 +1,53 @@ +# copied over from JSON::XS and modified to use JSON::PP + +use strict; +use warnings; +use Test::More; +BEGIN { plan tests => 16 }; + +BEGIN { $ENV{PERL_JSON_BACKEND} = 0; } + +use JSON::PP; + + +my $o1 = bless { a => 3 }, "XX"; +my $o2 = bless \(my $dummy = 1), "YY"; + +sub XX::TO_JSON { + {'__',""} +} + +my $js = JSON::PP->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/013_limit.t b/t/013_limit.t new file mode 100644 index 0000000..6aee693 --- /dev/null +++ b/t/013_limit.t @@ -0,0 +1,33 @@ +# copied over from JSON::XS and modified to use JSON::PP + +use strict; +use warnings; +use Test::More; +BEGIN { plan tests => 11 }; + +BEGIN { $ENV{PERL_JSON_BACKEND} = 0; } + +use JSON::PP; + + +my $def = 512; + +my $js = JSON::PP->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/014_latin1.t b/t/014_latin1.t new file mode 100644 index 0000000..cef9058 --- /dev/null +++ b/t/014_latin1.t @@ -0,0 +1,19 @@ +# copied over from JSON::XS and modified to use JSON::PP + +use strict; +use warnings; +use Test::More; +BEGIN { plan tests => 4 }; + +BEGIN { $ENV{PERL_JSON_BACKEND} = 0; } + +use JSON::PP; + +my $pp = JSON::PP->new->latin1->allow_nonref; + +ok ($pp->encode ("\x{12}\x{b6} ") eq "\"\\u0012\x{b6} \""); +ok ($pp->encode ("\x{12}\x{b6}\x{abc}") eq "\"\\u0012\x{b6}\\u0abc\""); + +ok ($pp->decode ("\"\\u0012\x{b6}\"" ) eq "\x{12}\x{b6}"); +ok ($pp->decode ("\"\\u0012\x{b6}\\u0abc\"") eq "\x{12}\x{b6}\x{abc}"); + diff --git a/t/015_prefix.t b/t/015_prefix.t new file mode 100644 index 0000000..df4f1b8 --- /dev/null +++ b/t/015_prefix.t @@ -0,0 +1,20 @@ +# copied over from JSON::XS and modified to use JSON::PP + +use strict; +use warnings; +use Test::More; +BEGIN { plan tests => 4 }; + +BEGIN { $ENV{PERL_JSON_BACKEND} = 0; } + +use JSON::PP; + +my $pp = JSON::PP->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/016_tied.t b/t/016_tied.t new file mode 100644 index 0000000..0561397 --- /dev/null +++ b/t/016_tied.t @@ -0,0 +1,25 @@ +# copied over from JSON::XS and modified to use JSON::PP + +use strict; +use warnings; +use Test::More; +BEGIN { plan tests => 2 }; + +BEGIN { $ENV{PERL_JSON_BACKEND} = 0; } + +use JSON::PP; +use Tie::Hash; +use Tie::Array; + + +my $js = JSON::PP->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/017_relaxed.t b/t/017_relaxed.t new file mode 100644 index 0000000..a49a3b4 --- /dev/null +++ b/t/017_relaxed.t @@ -0,0 +1,25 @@ +# copied over from JSON::XS and modified to use JSON::PP + +use strict; +use warnings; +use Test::More; +BEGIN { plan tests => 8 }; + +BEGIN { $ENV{PERL_JSON_BACKEND} = 0; } + +use utf8; +use JSON::PP; + + +my $json = JSON::PP->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/018_json_checker.t b/t/018_json_checker.t new file mode 100644 index 0000000..558861e --- /dev/null +++ b/t/018_json_checker.t @@ -0,0 +1,175 @@ +# copied over from JSON::XS and modified to use JSON::PP + +# 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} = 0; } + +use JSON::PP; + +# emulate JSON_checker default config +my $json = JSON::PP->new->utf8->max_depth(32)->canonical; + +my $vax_float = (pack("d",1) =~ /^[\x80\x10]\x40/); + +binmode DATA; + +for (;;) { + $/ = "\n# "; + chomp (my $test = ) + or last; + $/ = "\n"; + my $name = ; + 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/019_incr.t b/t/019_incr.t new file mode 100644 index 0000000..e8d9c26 --- /dev/null +++ b/t/019_incr.t @@ -0,0 +1,108 @@ +# copied over from JSON::XS and modified to use JSON::PP + +use strict; +no warnings; +use Test::More; +BEGIN { plan tests => 745 }; + +BEGIN { $ENV{PERL_JSON_BACKEND} = 0; } + +use JSON::PP; + +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::PP->new->allow_nonref (0), ' ["x\\"","\\u1000\\\\n\\nx",1,{"\\\\" :5 , "": "x"}]'; +splitter +JSON::PP->new->allow_nonref (0), '[ "x\\"","\\u1000\\\\n\\nx" , 1,{"\\\\ " :5 , "": " x"} ] '; +splitter +JSON::PP->new , '"test"'; +splitter +JSON::PP->new , ' "5" '; +splitter +JSON::PP->new , '-1e5'; +{ #SKIP_UNLESS_PP 3, 33 +splitter +JSON::PP->new , ' 0.00E+00 '; +} + +{ + my $text = '[5],{"":1} , [ 1,2, 3], {"3":null}'; + my $coder = JSON::PP->new; + 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 = JSON::PP->new; + $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::PP->new->max_size (5); + ok (!$coder->incr_parse ("[ "), "incsize1"); + eval { !$coder->incr_parse ("] ") }; ok ($@ =~ /6 bytes/, "incsize2 $@"); +} + +{ + my $coder = JSON::PP->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::PP->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/020_faihu.t b/t/020_faihu.t new file mode 100644 index 0000000..28bc18b --- /dev/null +++ b/t/020_faihu.t @@ -0,0 +1,30 @@ +# copied over from JSON::XS and modified to use JSON::PP + +# 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} = 0; } + +use JSON::PP; +use Encode qw(encode decode); + +use Test::More tests => 3; + +my ($faihu, $faihu_json, $roundtrip, $js) = "\x{10346}"; + +$js = JSON::PP->new->allow_nonref->ascii; +$faihu_json = $js->encode($faihu); +$roundtrip = $js->decode($faihu_json); +is ($roundtrip, $faihu, 'JSON in ASCII roundtrips correctly'); + +$js = JSON::PP->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::PP->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/020_unknown.t b/t/020_unknown.t new file mode 100644 index 0000000..4dceff8 --- /dev/null +++ b/t/020_unknown.t @@ -0,0 +1,46 @@ +use strict; +use warnings; + +use Test::More; +BEGIN { plan tests => 10 }; +BEGIN { $ENV{PERL_JSON_BACKEND} = 0; } + +use JSON::PP; + +my $json = JSON::PP->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]' ); + + +$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/021_evans.t b/t/021_evans.t new file mode 100644 index 0000000..723d8e2 --- /dev/null +++ b/t/021_evans.t @@ -0,0 +1,25 @@ +# copied over from JSON::XS and modified to use JSON::PP + +# adapted from a test by Martin Evans + +use strict; +use warnings; + +BEGIN { $ENV{PERL_JSON_BACKEND} = 0; } + +use JSON::PP; + +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::PP->new->encode ($data); +my $j = JSON::PP->new; +my $object = $j->incr_parse ($js); + +die "no object" if !$object; + +eval { $j->incr_text }; + +print $@ ? "not " : "", "ok 1 # $@\n"; + diff --git a/t/022_comment_at_eof.t b/t/022_comment_at_eof.t new file mode 100644 index 0000000..5cb7f21 --- /dev/null +++ b/t/022_comment_at_eof.t @@ -0,0 +1,50 @@ +# copied over from JSON::XS and modified to use JSON::PP + +# the original test case was provided by IKEGAMI@cpan.org + +use strict; +use warnings; + +use Test::More tests => 13; + +BEGIN { $ENV{PERL_JSON_BACKEND} = 0; } + +use JSON::PP; + +use Data::Dumper qw( Dumper ); + +sub decoder { + my ($str) = @_; + + my $json = JSON::PP->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/052_object.t b/t/052_object.t new file mode 100644 index 0000000..9b478f9 --- /dev/null +++ b/t/052_object.t @@ -0,0 +1,69 @@ +# copied over from JSON::XS and modified to use JSON::PP + +package JSON::PP::freeze; + +1; + +package JSON::PP::tojson; + +1; + +package main; + +use strict; +use warnings; +use Test::More; +BEGIN { plan tests => 20 }; +BEGIN { $^W = 0 } # hate + +BEGIN { $ENV{PERL_JSON_BACKEND} = 0; } + +use JSON::PP; + +my $json = JSON::PP->new->convert_blessed->allow_tags->allow_nonref; + +ok (1); + +sub JSON::PP::tojson::TO_JSON { + ok (@_ == 1); + ok (JSON::PP::tojson:: eq ref $_[0]); + ok ($_[0]{k} == 1); + 7 +} + +my $obj = bless { k => 1 }, JSON::PP::tojson::; + +ok (1); + +my $enc = $json->encode ($obj); +ok ($enc eq 7); + +ok (1); + +sub JSON::PP::freeze::FREEZE { + ok (@_ == 2); + ok ($_[1] eq "JSON"); + ok (JSON::PP::freeze:: eq ref $_[0]); + ok ($_[0]{k} == 1); + (3, 1, 2) +} + +sub JSON::PP::freeze::THAW { + ok (@_ == 5); + ok (JSON::PP::freeze:: eq $_[0]); + ok ($_[1] eq "JSON"); + ok ($_[2] == 3); + ok ($_[3] == 1); + ok ($_[4] == 2); + 777 +} + +$obj = bless { k => 1 }, JSON::PP::freeze::; +$enc = $json->encode ($obj); +ok ($enc eq '("JSON::PP::freeze")[3,1,2]'); + +my $dec = $json->decode ($enc); +ok ($dec eq 777); + +ok (1); + diff --git a/t/099_binary.pl b/t/099_binary.pl new file mode 100644 index 0000000..d0747da --- /dev/null +++ b/t/099_binary.pl @@ -0,0 +1,52 @@ +# copied over from JSON::XS and modified to use JSON::PP + +use strict; +use warnings; +use Test::More; +BEGIN { + if (defined(my $n= $ENV{JSONPP_CHUNK})) { + $ENV{JSONPP_FROM}= 1 + $n * 48; + $ENV{JSONPP_TO}= (1 + $n) * 48; + } + $ENV{JSONPP_FROM} = 1 unless defined $ENV{JSONPP_FROM}; + $ENV{JSONPP_TO} = 768 unless defined $ENV{JSONPP_TO}; +} +BEGIN { plan tests => 32 * ($ENV{JSONPP_TO} - $ENV{JSONPP_FROM} + 1) }; + +BEGIN { $ENV{PERL_JSON_BACKEND} = 0; } + +use JSON::PP; + + +sub test($) { + my $js; + + $js = JSON::PP->new->allow_nonref(0)->utf8->ascii->shrink->encode ([$_[0]]); + ok ($_[0] eq ((decode_json $js)->[0]), " - 0"); + $js = JSON::PP->new->allow_nonref(0)->utf8->ascii->encode ([$_[0]]); + ok ($_[0] eq (JSON::PP->new->utf8->shrink->decode($js))->[0], " - 1"); + + $js = JSON::PP->new->allow_nonref(0)->utf8->shrink->encode ([$_[0]]); + ok ($_[0] eq ((decode_json $js)->[0]), " - 2"); + $js = JSON::PP->new->allow_nonref(1)->utf8->encode ([$_[0]]); + ok ($_[0] eq (JSON::PP->new->utf8->shrink->decode($js))->[0], " - 3"); + + $js = JSON::PP->new->allow_nonref(1)->ascii->encode ([$_[0]]); + ok ($_[0] eq JSON::PP->new->decode ($js)->[0], " - 4"); + $js = JSON::PP->new->allow_nonref(0)->ascii->encode ([$_[0]]); + ok ($_[0] eq JSON::PP->new->shrink->decode ($js)->[0], " - 5"); + + $js = JSON::PP->new->allow_nonref(1)->shrink->encode ([$_[0]]); + ok ($_[0] eq JSON::PP->new->decode ($js)->[0], " - 6"); + $js = JSON::PP->new->allow_nonref(0)->encode ([$_[0]]); + ok ($_[0] eq JSON::PP->new->shrink->decode ($js)->[0], " - 7"); +} + +srand $ENV{JSONPP_FROM}; # doesn't help too much, but its at least more deterministic + +for ($ENV{JSONPP_FROM} .. $ENV{JSONPP_TO}) { + 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/099_binary00.t b/t/099_binary00.t new file mode 100644 index 0000000..9fa1c26 --- /dev/null +++ b/t/099_binary00.t @@ -0,0 +1,3 @@ +$0=~/binary(\d\d)/ or die "Could not detect chunk from '$0'"; +$ENV{JSONPP_CHUNK} = 0+$1; +do "./t/099_binary.pl"; diff --git a/t/099_binary01.t b/t/099_binary01.t new file mode 100644 index 0000000..9fa1c26 --- /dev/null +++ b/t/099_binary01.t @@ -0,0 +1,3 @@ +$0=~/binary(\d\d)/ or die "Could not detect chunk from '$0'"; +$ENV{JSONPP_CHUNK} = 0+$1; +do "./t/099_binary.pl"; diff --git a/t/099_binary02.t b/t/099_binary02.t new file mode 100644 index 0000000..9fa1c26 --- /dev/null +++ b/t/099_binary02.t @@ -0,0 +1,3 @@ +$0=~/binary(\d\d)/ or die "Could not detect chunk from '$0'"; +$ENV{JSONPP_CHUNK} = 0+$1; +do "./t/099_binary.pl"; diff --git a/t/099_binary03.t b/t/099_binary03.t new file mode 100644 index 0000000..9fa1c26 --- /dev/null +++ b/t/099_binary03.t @@ -0,0 +1,3 @@ +$0=~/binary(\d\d)/ or die "Could not detect chunk from '$0'"; +$ENV{JSONPP_CHUNK} = 0+$1; +do "./t/099_binary.pl"; diff --git a/t/099_binary04.t b/t/099_binary04.t new file mode 100644 index 0000000..9fa1c26 --- /dev/null +++ b/t/099_binary04.t @@ -0,0 +1,3 @@ +$0=~/binary(\d\d)/ or die "Could not detect chunk from '$0'"; +$ENV{JSONPP_CHUNK} = 0+$1; +do "./t/099_binary.pl"; diff --git a/t/099_binary05.t b/t/099_binary05.t new file mode 100644 index 0000000..9fa1c26 --- /dev/null +++ b/t/099_binary05.t @@ -0,0 +1,3 @@ +$0=~/binary(\d\d)/ or die "Could not detect chunk from '$0'"; +$ENV{JSONPP_CHUNK} = 0+$1; +do "./t/099_binary.pl"; diff --git a/t/099_binary06.t b/t/099_binary06.t new file mode 100644 index 0000000..9fa1c26 --- /dev/null +++ b/t/099_binary06.t @@ -0,0 +1,3 @@ +$0=~/binary(\d\d)/ or die "Could not detect chunk from '$0'"; +$ENV{JSONPP_CHUNK} = 0+$1; +do "./t/099_binary.pl"; diff --git a/t/099_binary07.t b/t/099_binary07.t new file mode 100644 index 0000000..9fa1c26 --- /dev/null +++ b/t/099_binary07.t @@ -0,0 +1,3 @@ +$0=~/binary(\d\d)/ or die "Could not detect chunk from '$0'"; +$ENV{JSONPP_CHUNK} = 0+$1; +do "./t/099_binary.pl"; diff --git a/t/099_binary08.t b/t/099_binary08.t new file mode 100644 index 0000000..9fa1c26 --- /dev/null +++ b/t/099_binary08.t @@ -0,0 +1,3 @@ +$0=~/binary(\d\d)/ or die "Could not detect chunk from '$0'"; +$ENV{JSONPP_CHUNK} = 0+$1; +do "./t/099_binary.pl"; diff --git a/t/099_binary09.t b/t/099_binary09.t new file mode 100644 index 0000000..9fa1c26 --- /dev/null +++ b/t/099_binary09.t @@ -0,0 +1,3 @@ +$0=~/binary(\d\d)/ or die "Could not detect chunk from '$0'"; +$ENV{JSONPP_CHUNK} = 0+$1; +do "./t/099_binary.pl"; diff --git a/t/099_binary10.t b/t/099_binary10.t new file mode 100644 index 0000000..9fa1c26 --- /dev/null +++ b/t/099_binary10.t @@ -0,0 +1,3 @@ +$0=~/binary(\d\d)/ or die "Could not detect chunk from '$0'"; +$ENV{JSONPP_CHUNK} = 0+$1; +do "./t/099_binary.pl"; diff --git a/t/099_binary11.t b/t/099_binary11.t new file mode 100644 index 0000000..9fa1c26 --- /dev/null +++ b/t/099_binary11.t @@ -0,0 +1,3 @@ +$0=~/binary(\d\d)/ or die "Could not detect chunk from '$0'"; +$ENV{JSONPP_CHUNK} = 0+$1; +do "./t/099_binary.pl"; diff --git a/t/099_binary12.t b/t/099_binary12.t new file mode 100644 index 0000000..9fa1c26 --- /dev/null +++ b/t/099_binary12.t @@ -0,0 +1,3 @@ +$0=~/binary(\d\d)/ or die "Could not detect chunk from '$0'"; +$ENV{JSONPP_CHUNK} = 0+$1; +do "./t/099_binary.pl"; diff --git a/t/099_binary13.t b/t/099_binary13.t new file mode 100644 index 0000000..9fa1c26 --- /dev/null +++ b/t/099_binary13.t @@ -0,0 +1,3 @@ +$0=~/binary(\d\d)/ or die "Could not detect chunk from '$0'"; +$ENV{JSONPP_CHUNK} = 0+$1; +do "./t/099_binary.pl"; diff --git a/t/099_binary14.t b/t/099_binary14.t new file mode 100644 index 0000000..9fa1c26 --- /dev/null +++ b/t/099_binary14.t @@ -0,0 +1,3 @@ +$0=~/binary(\d\d)/ or die "Could not detect chunk from '$0'"; +$ENV{JSONPP_CHUNK} = 0+$1; +do "./t/099_binary.pl"; diff --git a/t/099_binary15.t b/t/099_binary15.t new file mode 100644 index 0000000..9fa1c26 --- /dev/null +++ b/t/099_binary15.t @@ -0,0 +1,3 @@ +$0=~/binary(\d\d)/ or die "Could not detect chunk from '$0'"; +$ENV{JSONPP_CHUNK} = 0+$1; +do "./t/099_binary.pl"; diff --git a/t/104_sortby.t b/t/104_sortby.t new file mode 100644 index 0000000..1188e97 --- /dev/null +++ b/t/104_sortby.t @@ -0,0 +1,25 @@ + +use Test::More; +use strict; +use warnings; +BEGIN { plan tests => 3 }; +BEGIN { $ENV{PERL_JSON_BACKEND} = 0; } +use JSON::PP; +######################### + +my ($js,$obj); +my $pc = JSON::PP->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..56f415c --- /dev/null +++ b/t/105_esc_slash.t @@ -0,0 +1,16 @@ + +use Test::More; +use strict; +use warnings; +BEGIN { plan tests => 2 }; +BEGIN { $ENV{PERL_JSON_BACKEND} = 0; } +use JSON::PP; +######################### + +my $json = JSON::PP->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..20918bb --- /dev/null +++ b/t/106_allow_barekey.t @@ -0,0 +1,20 @@ + +use Test::More; +use strict; +use warnings; +BEGIN { plan tests => 2 }; +BEGIN { $ENV{PERL_JSON_BACKEND} = 0; } +use JSON::PP; +######################### + +my $json = JSON::PP->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..b3462f9 --- /dev/null +++ b/t/107_allow_singlequote.t @@ -0,0 +1,21 @@ + +use Test::More; +use strict; +use warnings; +BEGIN { plan tests => 4 }; +BEGIN { $ENV{PERL_JSON_BACKEND} = 0; } +use JSON::PP; +######################### + +my $json = JSON::PP->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..3282c85 --- /dev/null +++ b/t/108_decode.t @@ -0,0 +1,46 @@ +# +# decode on Perl 5.005, 5.6, 5.8 or later +# +use strict; +use warnings; +use Test::More; + +BEGIN { plan tests => 7 }; + +BEGIN { $ENV{PERL_JSON_BACKEND} = 0; } + +my $isASCII = ord "A" == 65; + +use JSON::PP; + +no utf8; + +my $json = JSON::PP->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(($isASCII) ? q|"\u00e3\u0081\u0082"| + : q|"\u00ce\u0043\u0043"|), + $str); + +utf8::decode($str); # usually UTF-8 flagged on, but no-op for 5.005. + +is($json->decode(q|"\u3042"|), $str); + + +# chr 0x12400, which was chosen because it has the same representation in +# both EBCDIC 1047 and 037 +my $utf8 = $json->decode(q|"\ud809\udc00"|); + +utf8::encode($utf8); # UTF-8 flagged off + +is($utf8, ($isASCII) ? "\xf0\x92\x90\x80" : "\xDE\x4A\x41\x41"); + +eval { $json->decode(q|{"action":"foo" "method":"bar","tid":1}|) }; +my $error = $@; +like $error => qr!""method":"bar","tid"..."!; diff --git a/t/109_encode.t b/t/109_encode.t new file mode 100644 index 0000000..bd0dcf4 --- /dev/null +++ b/t/109_encode.t @@ -0,0 +1,44 @@ +# +# decode on Perl 5.005, 5.6, 5.8 or later +# +use strict; +use warnings; +use Test::More; + +BEGIN { plan tests => 7 }; + +BEGIN { $ENV{PERL_JSON_BACKEND} = 0; } + +use JSON::PP; + +no utf8; + +my $json = JSON::PP->new->allow_nonref; + +# U+00B6 chosen because it works on both ASCII and EBCDIC +is($json->encode("¶"), q|"¶"|); # as is + +$json->ascii; + +is($json->encode("\xb6"), q|"\u00b6"|); # latin1 + +if (ord "A" == 65) { + is($json->encode("\xc2\xb6"), q|"\u00c2\u00b6"|); # utf8 + is($json->encode("¶"), q|"\u00c2\u00b6"|); # utf8 + is($json->encode('あ'), q|"\u00e3\u0081\u0082"|); +} +else { + if (ord '^' == 95) { # EBCDIC 1047 + is($json->encode("\x80\x65"), q|"\u0080\u0065"|); # utf8 + is($json->encode("¶"), q|"\u0080\u0065"|); # utf8 + } + else { # Assume EBCDIC 037 + is($json->encode("\x78\x64"), q|"\u0078\u0064"|); # utf8 + is($json->encode("¶"), q|"\u0078\u0064"|); # utf8 + } + + is($json->encode('あ'), (q|"\u00ce\u0043\u0043"|)); +} + +is($json->encode(chr hex 3042 ), q|"\u3042"|); +is($json->encode(chr hex 12345 ), q|"\ud808\udf45"|); diff --git a/t/110_bignum.t b/t/110_bignum.t new file mode 100644 index 0000000..99305dd --- /dev/null +++ b/t/110_bignum.t @@ -0,0 +1,51 @@ + +use strict; +use warnings; +use Test::More; +BEGIN { plan tests => 9 }; + +BEGIN { $ENV{PERL_JSON_BACKEND} = 0; } + +use JSON::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 = JSON::PP->new; + +$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_UNLESS_PP 2.91_03, 2 +$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_UNLESS_PP 2.90, 1 +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..681ce67 --- /dev/null +++ b/t/112_upgrade.t @@ -0,0 +1,25 @@ +use strict; +use warnings; +use Test::More; + +BEGIN { plan tests => 3 }; + +BEGIN { $ENV{PERL_JSON_BACKEND} = 0; } + +use JSON::PP; + +my $json = JSON::PP->new->allow_nonref->utf8; +my $str = '\\u00b6'; + +my $value = $json->decode( '"\\u00b6"' ); + +#use Devel::Peek; +#Dump( $value ); + +is( $value, chr 0xb6 ); + +ok( utf8::is_utf8( $value ) ); + +eval { $json->decode( '"' . chr(0xb6) . '"' ) }; +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..d4f7027 --- /dev/null +++ b/t/113_overloaded_eq.t @@ -0,0 +1,67 @@ +use strict; +use warnings; +use Test::More tests => 4; + +BEGIN { + $ENV{ PERL_JSON_BACKEND } = 0; +} + +use JSON::PP; + +my $json = JSON::PP->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 warnings; +use overload ( + 'eq' => sub { 0 }, + '""' => sub { $_[0] }, + fallback => 1, +); + +sub TO_JSON { + return $_[0]; +} + +package Bar; + +use strict; +use warnings; +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..2b3dfa7 --- /dev/null +++ b/t/114_decode_prefix.t @@ -0,0 +1,28 @@ +use strict; +use warnings; +use Test::More tests => 8; + +BEGIN { + $ENV{ PERL_JSON_BACKEND } = 0; +} + +use JSON::PP; + +my $json = JSON::PP->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..a8bed21 --- /dev/null +++ b/t/115_tie_ixhash.t @@ -0,0 +1,47 @@ + +use strict; +use warnings; +use Test::More; +BEGIN { plan tests => 2 }; + +BEGIN { $ENV{PERL_JSON_BACKEND} = 0; } + +use JSON::PP; + +# 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::PP->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..6ad5d5c --- /dev/null +++ b/t/116_incr_parse_fixed.t @@ -0,0 +1,24 @@ +use strict; +use warnings; +use Test::More tests => 4; + +use JSON::PP; + +my $json = JSON::PP->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::PP->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..bd80f51 --- /dev/null +++ b/t/117_numbers.t @@ -0,0 +1,25 @@ +use Test::More; +use strict; +use warnings; +BEGIN { $ENV{PERL_JSON_BACKEND} = 0; } +BEGIN { $ENV{PERL_JSON_PP_USE_B} = 0 } +use JSON::PP; + +#SKIP_ALL_UNLESS_PP 2.90 +#SKIP_ALL_IF_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..1019b39 --- /dev/null +++ b/t/118_boolean_values.t @@ -0,0 +1,81 @@ +use strict; +use warnings; +use Test::More; +BEGIN { $ENV{PERL_JSON_BACKEND} = 0; } +use JSON::PP; + +#SKIP_ALL_UNLESS_XS4_COMPAT + +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::PP; 1") { + push @tests, [JSON::PP::true(), JSON::PP::false(), '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 => 15 * @tests; + +my $json = JSON::PP->new; +for my $test (@tests) { + my ($true, $false, $true_class, $false_class, $incompat) = @$test; + + my $ret = $json->boolean_values($false, $true); + is $ret => $json, "returns the same object"; + 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"; + } + + $ret = $json->boolean_values(); + is $ret => $json, "returns the same object"; + 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/119_incr_parse_utf8.t b/t/119_incr_parse_utf8.t new file mode 100644 index 0000000..90916fb --- /dev/null +++ b/t/119_incr_parse_utf8.t @@ -0,0 +1,75 @@ +use strict; +use warnings; +use Test::More tests => 24; + +use utf8; +use JSON::PP; +use Encode; +use charnames qw< :full >; + +use vars qw< @vs >; + +############################################################ +### These first tests mimic the ones in `t/001_utf8.t` ### +############################################################ + +scalar eval { JSON::PP->new->allow_nonref (1)->utf8 (1)->incr_parse ('"ü"') }; +like $@, qr/malformed UTF-8/; + +ok (JSON::PP->new->allow_nonref (1)->incr_parse ('"ü"') eq "ü"); +ok (JSON::PP->new->allow_nonref (1)->incr_parse ('"\u00fc"') eq "ü"); +ok (JSON::PP->new->allow_nonref (1)->incr_parse ('"\ud801\udc02' . "\x{10204}\"") eq "\x{10402}\x{10204}"); +ok (JSON::PP->new->allow_nonref (1)->incr_parse ('"\"\n\\\\\r\t\f\b"') eq "\"\012\\\015\011\014\010"); + + +my $JSON_TXT = <utf8' ### +####################### + +@vs = eval { JSON::PP->new->utf8->incr_parse( $JSON_TXT ) }; +like $@, qr/Wide character in subroutine entry/; + + +@vs = eval { JSON::PP->new->utf8->incr_parse( encode 'UTF-8' => $JSON_TXT ) }; + +ok( !$@ ); +ok( scalar @vs == 3 ); + +is_deeply( \@vs, [ { a => "1" }, { b => "\N{BULLET}" }, { c => "3" } ] ); +is_deeply( $vs[0], { a => "1" } ); +is_deeply( $vs[1], { b => "\N{BULLET}" } ); +is_deeply( $vs[2], { c => "3" } ); + + +# Double-Encoded => "You Get What You Ask For" + +@vs = eval { JSON::PP->new->utf8->incr_parse( encode 'UTF-8' => ( encode 'UTF-8' => $JSON_TXT ) ) }; + +ok( !$@ ); +ok( scalar @vs == 3 ); + +is_deeply( \@vs, [ { a => "1" }, { b => "\x{E2}\x{80}\x{A2}" }, { c => "3" } ] ); +is_deeply( $vs[0], { a => "1" } ); +is_deeply( $vs[1], { b => "\x{E2}\x{80}\x{A2}" } ); +is_deeply( $vs[2], { c => "3" } ); + + +########################## +### Without '->utf8' ### +########################## + +@vs = eval { JSON::PP->new->incr_parse( $JSON_TXT ) }; + +ok( !$@ ); +ok( scalar @vs == 3 ); + +is_deeply( \@vs, [ { a => "1" }, { b => "\N{BULLET}" }, { c => "3" } ] ); +is_deeply( $vs[0], { a => "1" } ); +is_deeply( $vs[1], { b => "\N{BULLET}" } ); +is_deeply( $vs[2], { c => "3" } ); diff --git a/t/120_incr_parse_truncated.t b/t/120_incr_parse_truncated.t new file mode 100644 index 0000000..ea37ee4 --- /dev/null +++ b/t/120_incr_parse_truncated.t @@ -0,0 +1,218 @@ +use strict; +use warnings; +use Test::More; +use JSON::PP; + +plan tests => 19 * 3 + 1 * 6; + +sub run_test { + my ($input, $sub) = @_; + $sub->($input); +} + +run_test('{"one": 1}', sub { + my $input = shift; + my $coder = JSON::PP->new; + my $res = eval { $coder->incr_parse($input) }; + my $e = $@; # test more clobbers $@, we need it twice + ok ($res, "curly braces okay -- '$input'"); + ok (!$e, "no error -- '$input'"); + unlike ($e, qr/, or \} expected while parsing object\/hash/, "No '} expected' json string error"); +}); + +run_test('{"one": 1]', sub { + my $input = shift; + my $coder = JSON::PP->new; + my $res = eval { $coder->incr_parse($input) }; + my $e = $@; # test more clobbers $@, we need it twice + ok (!$res, "unbalanced curly braces -- '$input'"); + ok ($e, "got error -- '$input'"); + like ($e, qr/, or \} expected while parsing object\/hash/, "'} expected' json string error"); +}); + +run_test('"', sub { + my $input = shift; + my $coder = JSON::PP->new; + my $res = eval { $coder->incr_parse($input) }; + my $e = $@; # test more clobbers $@, we need it twice + ok (!$res, "truncated input='$input'"); + ok (!$e, "no error for input='$input'"); + unlike ($e, qr/, or \} expected while parsing object\/hash/, "No '} expected' json string error for input='$input'"); +}); + +run_test('{', sub { + my $input = shift; + my $coder = JSON::PP->new; + my $res = eval { $coder->incr_parse($input) }; + my $e = $@; # test more clobbers $@, we need it twice + ok (!$res, "truncated input='$input'"); + ok (!$e, "no error for input='$input'"); + unlike ($e, qr/, or \} expected while parsing object\/hash/, "No '} expected' json string error for input='$input'"); +}); + +run_test('[', sub { + my $input = shift; + my $coder = JSON::PP->new; + my $res = eval { $coder->incr_parse($input) }; + my $e = $@; # test more clobbers $@, we need it twice + ok (!$res, "truncated input='$input'"); + ok (!$e, "no error for input='$input'"); + unlike ($e, qr/, or \} expected while parsing object\/hash/, "No '} expected' json string error for input='$input'"); +}); + +run_test('}', sub { + my $input = shift; + my $coder = JSON::PP->new; + my $res = eval { $coder->incr_parse($input) }; + my $e = $@; # test more clobbers $@, we need it twice + ok (!$res, "truncated input='$input'"); + ok ($e, "no error for input='$input'"); + like ($e, qr/malformed JSON string/, "'malformed JSON string' json string error for input='$input'"); +}); + +run_test(']', sub { + my $input = shift; + my $coder = JSON::PP->new; + my $res = eval { $coder->incr_parse($input) }; + my $e = $@; # test more clobbers $@, we need it twice + ok (!$res, "truncated input='$input'"); + ok ($e, "no error for input='$input'"); + like ($e, qr/malformed JSON string/, "'malformed JSON string' json string error for input='$input'"); +}); + +run_test('1', sub { + my $input = shift; + my $coder = JSON::PP->new; + my $res = eval { $coder->incr_parse($input) }; + my $e = $@; # test more clobbers $@, we need it twice + ok ($res, "truncated input='$input'"); + ok (!$e, "no error for input='$input'"); + unlike ($e, qr/malformed JSON string/, "'malformed JSON string' json string error for input='$input'"); +}); + +run_test('1', sub { + my $input = shift; + my $coder = JSON::PP->new->allow_nonref(0); + my $res = eval { $coder->incr_parse($input) }; + my $e = $@; # test more clobbers $@, we need it twice + ok (!$res, "truncated input='$input'"); + ok ($e, "no error for input='$input'"); + like ($e, qr/JSON text must be an object or array/, "'JSON text must be an object or array' json string error for input='$input'"); +}); + +run_test('"1', sub { + my $input = shift; + my $coder = JSON::PP->new; + my $res = eval { $coder->incr_parse($input) }; + my $e = $@; # test more clobbers $@, we need it twice + ok (!$res, "truncated input='$input'"); + ok (!$e, "no error for input='$input'"); + unlike ($e, qr/malformed JSON string/, "'malformed JSON string' json string error for input='$input'"); +}); + +run_test('\\', sub { + my $input = shift; + my $coder = JSON::PP->new; + my $res = eval { $coder->incr_parse($input) }; + my $e = $@; # test more clobbers $@, we need it twice + ok (!$res, "truncated input='$input'"); + ok ($e, "no error for input='$input'"); + like ($e, qr/malformed JSON string/, "'malformed JSON string' json string error for input='$input'"); +}); + +run_test('{"one": "', sub { + my $input = shift; + my $coder = JSON::PP->new; + my $res = eval { $coder->incr_parse($input) }; + my $e = $@; # test more clobbers $@, we need it twice + ok (!$res, "truncated input='$input'"); + ok (!$e, "no error for input='$input'"); + unlike ($e, qr/, or \} expected while parsing object\/hash/, "No '} expected' json string error for input='$input'"); +}); + +run_test('{"one": {', sub { + my $input = shift; + my $coder = JSON::PP->new; + my $res = eval { $coder->incr_parse($input) }; + my $e = $@; # test more clobbers $@, we need it twice + ok (!$res, "truncated input='$input'"); + ok (!$e, "no error for input='$input'"); + unlike ($e, qr/, or \} expected while parsing object\/hash/, "No '} expected' json string error for input='$input'"); +}); + +run_test('{"one": [', sub { + my $input = shift; + my $coder = JSON::PP->new; + my $res = eval { $coder->incr_parse($input) }; + my $e = $@; # test more clobbers $@, we need it twice + ok (!$res, "truncated input='$input'"); + ok (!$e, "no error for input='$input'"); + unlike ($e, qr/, or \} expected while parsing object\/hash/, "No '} expected' json string error for input='$input'"); +}); + +run_test('{"one": t', sub { + my $input = shift; + my $coder = JSON::PP->new; + my $res = eval { $coder->incr_parse($input) }; + my $e = $@; # test more clobbers $@, we need it twice + ok (!$res, "truncated input='$input'"); + ok (!$e, "no error for input='$input'"); + unlike ($e, qr/, or \} expected while parsing object\/hash/, "No '} expected' json string error for input='$input'"); +}); + +run_test('{"one": \\', sub { + my $input = shift; + my $coder = JSON::PP->new; + my $res = eval { $coder->incr_parse($input) }; + my $e = $@; # test more clobbers $@, we need it twice + ok (!$res, "truncated input='$input'"); + ok (!$e, "no error for input='$input'"); + unlike ($e, qr/, or \} expected while parsing object\/hash/, "No '} expected' json string error for input='$input'"); +}); + +run_test('{"one": ', sub { + my $input = shift; + my $coder = JSON::PP->new; + my $res = eval { $coder->incr_parse($input) }; + my $e = $@; # test more clobbers $@, we need it twice + ok (!$res, "truncated input='$input'"); + ok (!$e, "no error for input='$input'"); + unlike ($e, qr/, or \} expected while parsing object\/hash/, "No '} expected' json string error for input='$input'"); +}); + +run_test('{"one": 1', sub { + my $input = shift; + my $coder = JSON::PP->new; + my $res = eval { $coder->incr_parse($input) }; + my $e = $@; # test more clobbers $@, we need it twice + ok (!$res, "truncated input='$input'"); + ok (!$e, "no error for input='$input'"); + unlike ($e, qr/, or \} expected while parsing object\/hash/, "No '} expected' json string error for input='$input'"); +}); + +run_test('{"one": {"two": 2', sub { + my $input = shift; + my $coder = JSON::PP->new; + my $res = eval { $coder->incr_parse($input) }; + my $e = $@; # test more clobbers $@, we need it twice + ok (!$res, "truncated '$input'"); + ok (!$e, "no error -- '$input'"); + unlike ($e, qr/, or \} expected while parsing object\/hash/, "No '} expected' json string error -- $input"); +}); + +# Test Appending Closing '}' Curly Bracket +run_test('{"one": 1', sub { + my $input = shift; + my $coder = JSON::PP->new; + my $res = eval { $coder->incr_parse($input) }; + my $e = $@; # test more clobbers $@, we need it twice + ok (!$res, "truncated input='$input'"); + ok (!$e, "no error for input='$input'"); + unlike ($e, qr/, or \} expected while parsing object\/hash/, "No '} expected' json string error for input='$input'"); + + $res = eval { $coder->incr_parse('}') }; + $e = $@; # test more clobbers $@, we need it twice + ok ($res, "truncated input='$input' . '}'"); + ok (!$e, "no error for input='$input' . '}'"); + unlike ($e, qr/, or \} expected while parsing object\/hash/, "No '} expected' json string error for input='$input' . '}'"); +}); diff --git a/t/core_bools.t b/t/core_bools.t new file mode 100644 index 0000000..c48093b --- /dev/null +++ b/t/core_bools.t @@ -0,0 +1,85 @@ +use strict; +use warnings; +use JSON::PP; +use Test::More; +BEGIN { + # this is only for JSON.pm + plan skip_all => 'no support for core boolean options' + unless JSON::PP->can('CORE_BOOL'); +} + +plan tests => 24; + +my $json = JSON::PP->new; + +is $json->get_core_bools, !!0, 'core_bools initially false'; + +$json->boolean_values(!!0, !!1); +SKIP: { + skip "core_bools option doesn't register as true for core bools without core boolean support", 1 + unless JSON::PP::CORE_BOOL; + + is $json->get_core_bools, !!1, 'core_bools true when setting bools to core bools'; +} + +$json->boolean_values(!!1, !!0); +is $json->get_core_bools, !!0, 'core_bools false when setting bools to anything other than correct core bools'; + +my $ret = $json->core_bools; +is $ret, $json, + "returns the same object"; + +my ($new_false, $new_true) = $json->get_boolean_values; + +# ensure this registers as true on older perls where the boolean values +# themselves can't be tracked. +is $json->get_core_bools, !!1, 'core_bools true when setting core_bools'; + +ok defined $new_true, "core true value is defined"; +ok defined $new_false, "core false value is defined"; + +ok !ref $new_true, "core true value is not blessed"; +ok !ref $new_false, "core falase value is not blessed"; + +{ + my @warnings; + local $SIG{__WARN__} = sub { + push @warnings, @_; + warn @_; + }; + + cmp_ok $new_true, 'eq', '1', 'core true value is "1"'; + cmp_ok $new_true, '==', 1, 'core true value is 1'; + + cmp_ok $new_false, 'eq', '', 'core false value is ""'; + cmp_ok $new_false, '==', 0, 'core false value is 0'; + + is scalar @warnings, 0, 'no warnings'; +} + +SKIP: { + skip "core boolean support needed to detect core booleans", 4 + unless JSON::PP::CORE_BOOL; + BEGIN { JSON::PP::CORE_BOOL and warnings->unimport(qw(experimental::builtin)) } + ok JSON::PP::is_bool($new_true), 'core true is a boolean'; + ok JSON::PP::is_bool($new_false), 'core false is a boolean'; + + ok builtin::is_bool($new_true), 'core true is a core boolean'; + ok builtin::is_bool($new_false), 'core false is a core boolean'; +} + +my $should_true = $json->allow_nonref(1)->decode('true'); +my $should_false = $json->allow_nonref(1)->decode('false'); + +ok !ref $should_true && $should_true, "JSON true turns into an unblessed true value"; +ok !ref $should_false && !$should_false, "JSON false turns into an unblessed false value"; + +SKIP: { + skip "core boolean support needed to detect core booleans", 4 + unless JSON::PP::CORE_BOOL; + ok JSON::PP::is_bool($should_true), 'decoded true is a boolean'; + ok JSON::PP::is_bool($should_false), 'decoded false is a boolean'; + + ok JSON::PP::is_bool($should_true), 'decoded true is a core boolean'; + ok JSON::PP::is_bool($should_false), 'decoded false is a core boolean'; +} diff --git a/t/gh_28_json_test_suite.t b/t/gh_28_json_test_suite.t new file mode 100644 index 0000000..3df2e6c --- /dev/null +++ b/t/gh_28_json_test_suite.t @@ -0,0 +1,58 @@ +# the following test cases are taken from JSONTestSuite +# by Nicolas Seriot (https://github.com/nst/JSONTestSuite) + +use strict; +use warnings; +use Test::More; + +BEGIN { plan tests => 20 }; + +BEGIN { $ENV{PERL_JSON_BACKEND} = 0; } + +use JSON::PP; + +my $DECODER = JSON::PP->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..e569d29 --- /dev/null +++ b/t/gh_29_trailing_false_value.t @@ -0,0 +1,14 @@ +use strict; +use warnings; +use Test::More; + +BEGIN { plan tests => 1 }; + +BEGIN { $ENV{PERL_JSON_BACKEND} = 0; } + +use JSON::PP; + +{ #SKIP_UNLESS_PP 2.90,1 + eval { JSON::PP->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..e9b88c0 --- /dev/null +++ b/t/rt_116998_wrong_character_offset.t @@ -0,0 +1,23 @@ +use strict; +use warnings; +use Test::More; +BEGIN { plan tests => 4 }; +BEGIN { $ENV{PERL_JSON_BACKEND} = 0; } +use JSON::PP; + +{ #SKIP_UNLESS_PP 2.90, 1 +eval { decode_json(qq({"foo":{"bar":42})) }; +like $@ => qr/offset 17/; # 16 +} + +eval { decode_json(qq(["foo",{"bar":42})) }; +like $@ => qr/offset 17/; + +{ #SKIP_UNLESS_PP 2.90, 1 +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_122270_old_xs_boolean.t b/t/rt_122270_old_xs_boolean.t new file mode 100644 index 0000000..a3deb48 --- /dev/null +++ b/t/rt_122270_old_xs_boolean.t @@ -0,0 +1,33 @@ +# copied over from JSON::XS and modified to use JSON::PP + +use strict; +use warnings; +use Test::More; +BEGIN { plan tests => 10 }; + +BEGIN { $ENV{PERL_JSON_BACKEND} = 0; } + +use utf8; +use JSON::PP; + +SKIP: { + skip "no JSON::XS < 3", 5 unless eval { require JSON::XS; JSON::XS->VERSION < 3 }; + + my $false = JSON::XS::false(); + ok (JSON::PP::is_bool $false); + ok (++$false == 1); + ok (!JSON::PP::is_bool $false); + ok (!JSON::PP::is_bool "JSON::PP::Boolean"); + ok (!JSON::PP::is_bool {}); # GH-34 +} + +SKIP: { + skip "no Types::Serialiser 0.01", 5 unless eval { require JSON::XS; JSON::XS->VERSION(3.00); require Types::Serialiser; Types::Serialiser->VERSION == 0.01 }; + + my $false = JSON::XS::false(); + ok (JSON::PP::is_bool $false); + ok (++$false == 1); + ok (!JSON::PP::is_bool $false); + ok (!JSON::PP::is_bool "JSON::PP::Boolean"); + ok (!JSON::PP::is_bool {}); # GH-34 +} diff --git a/t/rt_90071_incr_parse.t b/t/rt_90071_incr_parse.t new file mode 100644 index 0000000..cc07216 --- /dev/null +++ b/t/rt_90071_incr_parse.t @@ -0,0 +1,30 @@ +use strict; +use warnings; +use Test::More; +BEGIN { $ENV{PERL_JSON_BACKEND} = 0; } +use JSON::PP; + +#SKIP_ALL_UNLESS_PP 2.90 + +BEGIN { plan tests => 2 }; + +my $json = JSON::PP->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/zero-mojibake.t b/t/zero-mojibake.t new file mode 100644 index 0000000..8d5185d --- /dev/null +++ b/t/zero-mojibake.t @@ -0,0 +1,22 @@ +use strict; +use warnings; +use Test::More; +BEGIN { plan tests => 1 }; + +BEGIN { $ENV{PERL_JSON_BACKEND} = 0; } + +use JSON::PP; + +my $json = JSON::PP->new; + +my $input = q[ +{ + "dynamic_config" : 0, + "x_contributors" : [ + "大沢 和宏", + "Ævar Arnfjörð" + ] +} +]; +eval { $json->decode($input) }; +is $@, '', 'decodes 0 with mojibake without error'; -- 2.34.1