JSON.pm 66 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267
  1. package JSON;
  2. use strict;
  3. use Carp ();
  4. use base qw(Exporter);
  5. @JSON::EXPORT = qw(from_json to_json jsonToObj objToJson encode_json decode_json);
  6. BEGIN {
  7. $JSON::VERSION = '2.53';
  8. $JSON::DEBUG = 0 unless (defined $JSON::DEBUG);
  9. $JSON::DEBUG = $ENV{ PERL_JSON_DEBUG } if exists $ENV{ PERL_JSON_DEBUG };
  10. }
  11. my $Module_XS = 'JSON::XS';
  12. my $Module_PP = 'JSON::PP';
  13. my $Module_bp = 'JSON::backportPP'; # included in JSON distribution
  14. my $PP_Version = '2.27200';
  15. my $XS_Version = '2.27';
  16. # XS and PP common methods
  17. my @PublicMethods = qw/
  18. ascii latin1 utf8 pretty indent space_before space_after relaxed canonical allow_nonref
  19. allow_blessed convert_blessed filter_json_object filter_json_single_key_object
  20. shrink max_depth max_size encode decode decode_prefix allow_unknown
  21. /;
  22. my @Properties = qw/
  23. ascii latin1 utf8 indent space_before space_after relaxed canonical allow_nonref
  24. allow_blessed convert_blessed shrink max_depth max_size allow_unknown
  25. /;
  26. my @XSOnlyMethods = qw//; # Currently nothing
  27. my @PPOnlyMethods = qw/
  28. indent_length sort_by
  29. allow_singlequote allow_bignum loose allow_barekey escape_slash as_nonblessed
  30. /; # JSON::PP specific
  31. # used in _load_xs and _load_pp ($INSTALL_ONLY is not used currently)
  32. my $_INSTALL_DONT_DIE = 1; # When _load_xs fails to load XS, don't die.
  33. my $_INSTALL_ONLY = 2; # Don't call _set_methods()
  34. my $_ALLOW_UNSUPPORTED = 0;
  35. my $_UNIV_CONV_BLESSED = 0;
  36. my $_USSING_bpPP = 0;
  37. # Check the environment variable to decide worker module.
  38. unless ($JSON::Backend) {
  39. $JSON::DEBUG and Carp::carp("Check used worker module...");
  40. my $backend = exists $ENV{PERL_JSON_BACKEND} ? $ENV{PERL_JSON_BACKEND} : 1;
  41. if ($backend eq '1' or $backend =~ /JSON::XS\s*,\s*JSON::PP/) {
  42. _load_xs($_INSTALL_DONT_DIE) or _load_pp();
  43. }
  44. elsif ($backend eq '0' or $backend eq 'JSON::PP') {
  45. _load_pp();
  46. }
  47. elsif ($backend eq '2' or $backend eq 'JSON::XS') {
  48. _load_xs();
  49. }
  50. elsif ($backend eq 'JSON::backportPP') {
  51. $_USSING_bpPP = 1;
  52. _load_pp();
  53. }
  54. else {
  55. Carp::croak "The value of environmental variable 'PERL_JSON_BACKEND' is invalid.";
  56. }
  57. }
  58. sub import {
  59. my $pkg = shift;
  60. my @what_to_export;
  61. my $no_export;
  62. for my $tag (@_) {
  63. if ($tag eq '-support_by_pp') {
  64. if (!$_ALLOW_UNSUPPORTED++) {
  65. JSON::Backend::XS
  66. ->support_by_pp(@PPOnlyMethods) if ($JSON::Backend eq $Module_XS);
  67. }
  68. next;
  69. }
  70. elsif ($tag eq '-no_export') {
  71. $no_export++, next;
  72. }
  73. elsif ( $tag eq '-convert_blessed_universally' ) {
  74. eval q|
  75. require B;
  76. *UNIVERSAL::TO_JSON = sub {
  77. my $b_obj = B::svref_2object( $_[0] );
  78. return $b_obj->isa('B::HV') ? { %{ $_[0] } }
  79. : $b_obj->isa('B::AV') ? [ @{ $_[0] } ]
  80. : undef
  81. ;
  82. }
  83. | if ( !$_UNIV_CONV_BLESSED++ );
  84. next;
  85. }
  86. push @what_to_export, $tag;
  87. }
  88. return if ($no_export);
  89. __PACKAGE__->export_to_level(1, $pkg, @what_to_export);
  90. }
  91. # OBSOLETED
  92. sub jsonToObj {
  93. my $alternative = 'from_json';
  94. if (defined $_[0] and UNIVERSAL::isa($_[0], 'JSON')) {
  95. shift @_; $alternative = 'decode';
  96. }
  97. Carp::carp "'jsonToObj' will be obsoleted. Please use '$alternative' instead.";
  98. return JSON::from_json(@_);
  99. };
  100. sub objToJson {
  101. my $alternative = 'to_json';
  102. if (defined $_[0] and UNIVERSAL::isa($_[0], 'JSON')) {
  103. shift @_; $alternative = 'encode';
  104. }
  105. Carp::carp "'objToJson' will be obsoleted. Please use '$alternative' instead.";
  106. JSON::to_json(@_);
  107. };
  108. # INTERFACES
  109. sub to_json ($@) {
  110. if (
  111. ref($_[0]) eq 'JSON'
  112. or (@_ > 2 and $_[0] eq 'JSON')
  113. ) {
  114. Carp::croak "to_json should not be called as a method.";
  115. }
  116. my $json = new JSON;
  117. if (@_ == 2 and ref $_[1] eq 'HASH') {
  118. my $opt = $_[1];
  119. for my $method (keys %$opt) {
  120. $json->$method( $opt->{$method} );
  121. }
  122. }
  123. $json->encode($_[0]);
  124. }
  125. sub from_json ($@) {
  126. if ( ref($_[0]) eq 'JSON' or $_[0] eq 'JSON' ) {
  127. Carp::croak "from_json should not be called as a method.";
  128. }
  129. my $json = new JSON;
  130. if (@_ == 2 and ref $_[1] eq 'HASH') {
  131. my $opt = $_[1];
  132. for my $method (keys %$opt) {
  133. $json->$method( $opt->{$method} );
  134. }
  135. }
  136. return $json->decode( $_[0] );
  137. }
  138. sub true { $JSON::true }
  139. sub false { $JSON::false }
  140. sub null { undef; }
  141. sub require_xs_version { $XS_Version; }
  142. sub backend {
  143. my $proto = shift;
  144. $JSON::Backend;
  145. }
  146. #*module = *backend;
  147. sub is_xs {
  148. return $_[0]->module eq $Module_XS;
  149. }
  150. sub is_pp {
  151. return not $_[0]->xs;
  152. }
  153. sub pureperl_only_methods { @PPOnlyMethods; }
  154. sub property {
  155. my ($self, $name, $value) = @_;
  156. if (@_ == 1) {
  157. my %props;
  158. for $name (@Properties) {
  159. my $method = 'get_' . $name;
  160. if ($name eq 'max_size') {
  161. my $value = $self->$method();
  162. $props{$name} = $value == 1 ? 0 : $value;
  163. next;
  164. }
  165. $props{$name} = $self->$method();
  166. }
  167. return \%props;
  168. }
  169. elsif (@_ > 3) {
  170. Carp::croak('property() can take only the option within 2 arguments.');
  171. }
  172. elsif (@_ == 2) {
  173. if ( my $method = $self->can('get_' . $name) ) {
  174. if ($name eq 'max_size') {
  175. my $value = $self->$method();
  176. return $value == 1 ? 0 : $value;
  177. }
  178. $self->$method();
  179. }
  180. }
  181. else {
  182. $self->$name($value);
  183. }
  184. }
  185. # INTERNAL
  186. sub _load_xs {
  187. my $opt = shift;
  188. $JSON::DEBUG and Carp::carp "Load $Module_XS.";
  189. # if called after install module, overload is disable.... why?
  190. JSON::Boolean::_overrride_overload($Module_XS);
  191. JSON::Boolean::_overrride_overload($Module_PP);
  192. eval qq|
  193. use $Module_XS $XS_Version ();
  194. |;
  195. if ($@) {
  196. if (defined $opt and $opt & $_INSTALL_DONT_DIE) {
  197. $JSON::DEBUG and Carp::carp "Can't load $Module_XS...($@)";
  198. return 0;
  199. }
  200. Carp::croak $@;
  201. }
  202. unless (defined $opt and $opt & $_INSTALL_ONLY) {
  203. _set_module( $JSON::Backend = $Module_XS );
  204. my $data = join("", <DATA>); # this code is from Jcode 2.xx.
  205. close(DATA);
  206. eval $data;
  207. JSON::Backend::XS->init;
  208. }
  209. return 1;
  210. };
  211. sub _load_pp {
  212. my $opt = shift;
  213. my $backend = $_USSING_bpPP ? $Module_bp : $Module_PP;
  214. $JSON::DEBUG and Carp::carp "Load $backend.";
  215. # if called after install module, overload is disable.... why?
  216. JSON::Boolean::_overrride_overload($Module_XS);
  217. JSON::Boolean::_overrride_overload($backend);
  218. if ( $_USSING_bpPP ) {
  219. eval qq| require $backend |;
  220. }
  221. else {
  222. eval qq| use $backend $PP_Version () |;
  223. }
  224. if ($@) {
  225. if ( $backend eq $Module_PP ) {
  226. $JSON::DEBUG and Carp::carp "Can't load $Module_PP ($@), so try to load $Module_bp";
  227. $_USSING_bpPP++;
  228. $backend = $Module_bp;
  229. JSON::Boolean::_overrride_overload($backend);
  230. local $^W; # if PP installed but invalid version, backportPP redifines methods.
  231. eval qq| require $Module_bp |;
  232. }
  233. Carp::croak $@ if $@;
  234. }
  235. unless (defined $opt and $opt & $_INSTALL_ONLY) {
  236. _set_module( $JSON::Backend = $Module_PP ); # even if backportPP, set $Backend with 'JSON::PP'
  237. JSON::Backend::PP->init;
  238. }
  239. };
  240. sub _set_module {
  241. return if defined $JSON::true;
  242. my $module = shift;
  243. local $^W;
  244. no strict qw(refs);
  245. $JSON::true = ${"$module\::true"};
  246. $JSON::false = ${"$module\::false"};
  247. push @JSON::ISA, $module;
  248. push @{"$module\::Boolean::ISA"}, qw(JSON::Boolean);
  249. *{"JSON::is_bool"} = \&{"$module\::is_bool"};
  250. for my $method ($module eq $Module_XS ? @PPOnlyMethods : @XSOnlyMethods) {
  251. *{"JSON::$method"} = sub {
  252. Carp::carp("$method is not supported in $module.");
  253. $_[0];
  254. };
  255. }
  256. return 1;
  257. }
  258. #
  259. # JSON Boolean
  260. #
  261. package JSON::Boolean;
  262. my %Installed;
  263. sub _overrride_overload {
  264. return if ($Installed{ $_[0] }++);
  265. my $boolean = $_[0] . '::Boolean';
  266. eval sprintf(q|
  267. package %s;
  268. use overload (
  269. '""' => sub { ${$_[0]} == 1 ? 'true' : 'false' },
  270. 'eq' => sub {
  271. my ($obj, $op) = ref ($_[0]) ? ($_[0], $_[1]) : ($_[1], $_[0]);
  272. if ($op eq 'true' or $op eq 'false') {
  273. return "$obj" eq 'true' ? 'true' eq $op : 'false' eq $op;
  274. }
  275. else {
  276. return $obj ? 1 == $op : 0 == $op;
  277. }
  278. },
  279. );
  280. |, $boolean);
  281. if ($@) { Carp::croak $@; }
  282. return 1;
  283. }
  284. #
  285. # Helper classes for Backend Module (PP)
  286. #
  287. package JSON::Backend::PP;
  288. sub init {
  289. local $^W;
  290. no strict qw(refs); # this routine may be called after JSON::Backend::XS init was called.
  291. *{"JSON::decode_json"} = \&{"JSON::PP::decode_json"};
  292. *{"JSON::encode_json"} = \&{"JSON::PP::encode_json"};
  293. *{"JSON::PP::is_xs"} = sub { 0 };
  294. *{"JSON::PP::is_pp"} = sub { 1 };
  295. return 1;
  296. }
  297. #
  298. # To save memory, the below lines are read only when XS backend is used.
  299. #
  300. package JSON;
  301. 1;
  302. __DATA__
  303. #
  304. # Helper classes for Backend Module (XS)
  305. #
  306. package JSON::Backend::XS;
  307. use constant INDENT_LENGTH_FLAG => 15 << 12;
  308. use constant UNSUPPORTED_ENCODE_FLAG => {
  309. ESCAPE_SLASH => 0x00000010,
  310. ALLOW_BIGNUM => 0x00000020,
  311. AS_NONBLESSED => 0x00000040,
  312. EXPANDED => 0x10000000, # for developer's
  313. };
  314. use constant UNSUPPORTED_DECODE_FLAG => {
  315. LOOSE => 0x00000001,
  316. ALLOW_BIGNUM => 0x00000002,
  317. ALLOW_BAREKEY => 0x00000004,
  318. ALLOW_SINGLEQUOTE => 0x00000008,
  319. EXPANDED => 0x20000000, # for developer's
  320. };
  321. sub init {
  322. local $^W;
  323. no strict qw(refs);
  324. *{"JSON::decode_json"} = \&{"JSON::XS::decode_json"};
  325. *{"JSON::encode_json"} = \&{"JSON::XS::encode_json"};
  326. *{"JSON::XS::is_xs"} = sub { 1 };
  327. *{"JSON::XS::is_pp"} = sub { 0 };
  328. return 1;
  329. }
  330. sub support_by_pp {
  331. my ($class, @methods) = @_;
  332. local $^W;
  333. no strict qw(refs);
  334. my $JSON_XS_encode_orignal = \&JSON::XS::encode;
  335. my $JSON_XS_decode_orignal = \&JSON::XS::decode;
  336. my $JSON_XS_incr_parse_orignal = \&JSON::XS::incr_parse;
  337. *JSON::XS::decode = \&JSON::Backend::XS::Supportable::_decode;
  338. *JSON::XS::encode = \&JSON::Backend::XS::Supportable::_encode;
  339. *JSON::XS::incr_parse = \&JSON::Backend::XS::Supportable::_incr_parse;
  340. *{JSON::XS::_original_decode} = $JSON_XS_decode_orignal;
  341. *{JSON::XS::_original_encode} = $JSON_XS_encode_orignal;
  342. *{JSON::XS::_original_incr_parse} = $JSON_XS_incr_parse_orignal;
  343. push @JSON::Backend::XS::Supportable::ISA, 'JSON';
  344. my $pkg = 'JSON::Backend::XS::Supportable';
  345. *{JSON::new} = sub {
  346. my $proto = new JSON::XS; $$proto = 0;
  347. bless $proto, $pkg;
  348. };
  349. for my $method (@methods) {
  350. my $flag = uc($method);
  351. my $type |= (UNSUPPORTED_ENCODE_FLAG->{$flag} || 0);
  352. $type |= (UNSUPPORTED_DECODE_FLAG->{$flag} || 0);
  353. next unless($type);
  354. $pkg->_make_unsupported_method($method => $type);
  355. }
  356. push @{"JSON::XS::Boolean::ISA"}, qw(JSON::PP::Boolean);
  357. push @{"JSON::PP::Boolean::ISA"}, qw(JSON::Boolean);
  358. $JSON::DEBUG and Carp::carp("set -support_by_pp mode.");
  359. return 1;
  360. }
  361. #
  362. # Helper classes for XS
  363. #
  364. package JSON::Backend::XS::Supportable;
  365. $Carp::Internal{'JSON::Backend::XS::Supportable'} = 1;
  366. sub _make_unsupported_method {
  367. my ($pkg, $method, $type) = @_;
  368. local $^W;
  369. no strict qw(refs);
  370. *{"$pkg\::$method"} = sub {
  371. local $^W;
  372. if (defined $_[1] ? $_[1] : 1) {
  373. ${$_[0]} |= $type;
  374. }
  375. else {
  376. ${$_[0]} &= ~$type;
  377. }
  378. $_[0];
  379. };
  380. *{"$pkg\::get_$method"} = sub {
  381. ${$_[0]} & $type ? 1 : '';
  382. };
  383. }
  384. sub _set_for_pp {
  385. JSON::_load_pp( $_INSTALL_ONLY );
  386. my $type = shift;
  387. my $pp = new JSON::PP;
  388. my $prop = $_[0]->property;
  389. for my $name (keys %$prop) {
  390. $pp->$name( $prop->{$name} ? $prop->{$name} : 0 );
  391. }
  392. my $unsupported = $type eq 'encode' ? JSON::Backend::XS::UNSUPPORTED_ENCODE_FLAG
  393. : JSON::Backend::XS::UNSUPPORTED_DECODE_FLAG;
  394. my $flags = ${$_[0]} || 0;
  395. for my $name (keys %$unsupported) {
  396. next if ($name eq 'EXPANDED'); # for developer's
  397. my $enable = ($flags & $unsupported->{$name}) ? 1 : 0;
  398. my $method = lc $name;
  399. $pp->$method($enable);
  400. }
  401. $pp->indent_length( $_[0]->get_indent_length );
  402. return $pp;
  403. }
  404. sub _encode { # using with PP encod
  405. if (${$_[0]}) {
  406. _set_for_pp('encode' => @_)->encode($_[1]);
  407. }
  408. else {
  409. $_[0]->_original_encode( $_[1] );
  410. }
  411. }
  412. sub _decode { # if unsupported-flag is set, use PP
  413. if (${$_[0]}) {
  414. _set_for_pp('decode' => @_)->decode($_[1]);
  415. }
  416. else {
  417. $_[0]->_original_decode( $_[1] );
  418. }
  419. }
  420. sub decode_prefix { # if unsupported-flag is set, use PP
  421. _set_for_pp('decode' => @_)->decode_prefix($_[1]);
  422. }
  423. sub _incr_parse {
  424. if (${$_[0]}) {
  425. _set_for_pp('decode' => @_)->incr_parse($_[1]);
  426. }
  427. else {
  428. $_[0]->_original_incr_parse( $_[1] );
  429. }
  430. }
  431. sub get_indent_length {
  432. ${$_[0]} << 4 >> 16;
  433. }
  434. sub indent_length {
  435. my $length = $_[1];
  436. if (!defined $length or $length > 15 or $length < 0) {
  437. Carp::carp "The acceptable range of indent_length() is 0 to 15.";
  438. }
  439. else {
  440. local $^W;
  441. $length <<= 12;
  442. ${$_[0]} &= ~ JSON::Backend::XS::INDENT_LENGTH_FLAG;
  443. ${$_[0]} |= $length;
  444. *JSON::XS::encode = \&JSON::Backend::XS::Supportable::_encode;
  445. }
  446. $_[0];
  447. }
  448. 1;
  449. __END__
  450. =head1 NAME
  451. JSON - JSON (JavaScript Object Notation) encoder/decoder
  452. =head1 SYNOPSIS
  453. use JSON; # imports encode_json, decode_json, to_json and from_json.
  454. # simple and fast interfaces (expect/generate UTF-8)
  455. $utf8_encoded_json_text = encode_json $perl_hash_or_arrayref;
  456. $perl_hash_or_arrayref = decode_json $utf8_encoded_json_text;
  457. # OO-interface
  458. $json = JSON->new->allow_nonref;
  459. $json_text = $json->encode( $perl_scalar );
  460. $perl_scalar = $json->decode( $json_text );
  461. $pretty_printed = $json->pretty->encode( $perl_scalar ); # pretty-printing
  462. # If you want to use PP only support features, call with '-support_by_pp'
  463. # When XS unsupported feature is enable, using PP (de|en)code instead of XS ones.
  464. use JSON -support_by_pp;
  465. # option-acceptable interfaces (expect/generate UNICODE by default)
  466. $json_text = to_json( $perl_scalar, { ascii => 1, pretty => 1 } );
  467. $perl_scalar = from_json( $json_text, { utf8 => 1 } );
  468. # Between (en|de)code_json and (to|from)_json, if you want to write
  469. # a code which communicates to an outer world (encoded in UTF-8),
  470. # recommend to use (en|de)code_json.
  471. =head1 VERSION
  472. 2.53
  473. This version is compatible with JSON::XS B<2.27> and later.
  474. =head1 NOTE
  475. JSON::PP was inculded in C<JSON> distribution.
  476. It comes to be a perl core module in Perl 5.14.
  477. And L<JSON::PP> will be split away it.
  478. C<JSON> distribution will inculde yet another JSON::PP modules.
  479. They are JSNO::backportPP and so on. JSON.pm should work as it did at all.
  480. =head1 DESCRIPTION
  481. ************************** CAUTION ********************************
  482. * This is 'JSON module version 2' and there are many differences *
  483. * to version 1.xx *
  484. * Please check your applications useing old version. *
  485. * See to 'INCOMPATIBLE CHANGES TO OLD VERSION' *
  486. *******************************************************************
  487. JSON (JavaScript Object Notation) is a simple data format.
  488. See to L<http://www.json.org/> and C<RFC4627>(L<http://www.ietf.org/rfc/rfc4627.txt>).
  489. This module converts Perl data structures to JSON and vice versa using either
  490. L<JSON::XS> or L<JSON::PP>.
  491. JSON::XS is the fastest and most proper JSON module on CPAN which must be
  492. compiled and installed in your environment.
  493. JSON::PP is a pure-Perl module which is bundled in this distribution and
  494. has a strong compatibility to JSON::XS.
  495. This module try to use JSON::XS by default and fail to it, use JSON::PP instead.
  496. So its features completely depend on JSON::XS or JSON::PP.
  497. See to L<BACKEND MODULE DECISION>.
  498. To distinguish the module name 'JSON' and the format type JSON,
  499. the former is quoted by CE<lt>E<gt> (its results vary with your using media),
  500. and the latter is left just as it is.
  501. Module name : C<JSON>
  502. Format type : JSON
  503. =head2 FEATURES
  504. =over
  505. =item * correct unicode handling
  506. This module (i.e. backend modules) knows how to handle Unicode, documents
  507. how and when it does so, and even documents what "correct" means.
  508. Even though there are limitations, this feature is available since Perl version 5.6.
  509. JSON::XS requires Perl 5.8.2 (but works correctly in 5.8.8 or later), so in older versions
  510. C<JSON> sholud call JSON::PP as the backend which can be used since Perl 5.005.
  511. With Perl 5.8.x JSON::PP works, but from 5.8.0 to 5.8.2, because of a Perl side problem,
  512. JSON::PP works slower in the versions. And in 5.005, the Unicode handling is not available.
  513. See to L<JSON::PP/UNICODE HANDLING ON PERLS> for more information.
  514. See also to L<JSON::XS/A FEW NOTES ON UNICODE AND PERL>
  515. and L<JSON::XS/ENCODING/CODESET_FLAG_NOTES>.
  516. =item * round-trip integrity
  517. When you serialise a perl data structure using only data types supported
  518. by JSON and Perl, the deserialised data structure is identical on the Perl
  519. level. (e.g. the string "2.0" doesn't suddenly become "2" just because
  520. it looks like a number). There I<are> minor exceptions to this, read the
  521. L</MAPPING> section below to learn about those.
  522. =item * strict checking of JSON correctness
  523. There is no guessing, no generating of illegal JSON texts by default,
  524. and only JSON is accepted as input by default (the latter is a security
  525. feature).
  526. See to L<JSON::XS/FEATURES> and L<JSON::PP/FEATURES>.
  527. =item * fast
  528. This module returns a JSON::XS object itself if available.
  529. Compared to other JSON modules and other serialisers such as Storable,
  530. JSON::XS usually compares favourably in terms of speed, too.
  531. If not available, C<JSON> returns a JSON::PP object instead of JSON::XS and
  532. it is very slow as pure-Perl.
  533. =item * simple to use
  534. This module has both a simple functional interface as well as an
  535. object oriented interface interface.
  536. =item * reasonably versatile output formats
  537. You can choose between the most compact guaranteed-single-line format possible
  538. (nice for simple line-based protocols), a pure-ASCII format (for when your transport
  539. is not 8-bit clean, still supports the whole Unicode range), or a pretty-printed
  540. format (for when you want to read that stuff). Or you can combine those features
  541. in whatever way you like.
  542. =back
  543. =head1 FUNCTIONAL INTERFACE
  544. Some documents are copied and modified from L<JSON::XS/FUNCTIONAL INTERFACE>.
  545. C<to_json> and C<from_json> are additional functions.
  546. =head2 encode_json
  547. $json_text = encode_json $perl_scalar
  548. Converts the given Perl data structure to a UTF-8 encoded, binary string.
  549. This function call is functionally identical to:
  550. $json_text = JSON->new->utf8->encode($perl_scalar)
  551. =head2 decode_json
  552. $perl_scalar = decode_json $json_text
  553. The opposite of C<encode_json>: expects an UTF-8 (binary) string and tries
  554. to parse that as an UTF-8 encoded JSON text, returning the resulting
  555. reference.
  556. This function call is functionally identical to:
  557. $perl_scalar = JSON->new->utf8->decode($json_text)
  558. =head2 to_json
  559. $json_text = to_json($perl_scalar)
  560. Converts the given Perl data structure to a json string.
  561. This function call is functionally identical to:
  562. $json_text = JSON->new->encode($perl_scalar)
  563. Takes a hash reference as the second.
  564. $json_text = to_json($perl_scalar, $flag_hashref)
  565. So,
  566. $json_text = to_json($perl_scalar, {utf8 => 1, pretty => 1})
  567. equivalent to:
  568. $json_text = JSON->new->utf8(1)->pretty(1)->encode($perl_scalar)
  569. If you want to write a modern perl code which communicates to outer world,
  570. you should use C<encode_json> (supposed that JSON data are encoded in UTF-8).
  571. =head2 from_json
  572. $perl_scalar = from_json($json_text)
  573. The opposite of C<to_json>: expects a json string and tries
  574. to parse it, returning the resulting reference.
  575. This function call is functionally identical to:
  576. $perl_scalar = JSON->decode($json_text)
  577. Takes a hash reference as the second.
  578. $perl_scalar = from_json($json_text, $flag_hashref)
  579. So,
  580. $perl_scalar = from_json($json_text, {utf8 => 1})
  581. equivalent to:
  582. $perl_scalar = JSON->new->utf8(1)->decode($json_text)
  583. If you want to write a modern perl code which communicates to outer world,
  584. you should use C<decode_json> (supposed that JSON data are encoded in UTF-8).
  585. =head2 JSON::is_bool
  586. $is_boolean = JSON::is_bool($scalar)
  587. Returns true if the passed scalar represents either JSON::true or
  588. JSON::false, two constants that act like C<1> and C<0> respectively
  589. and are also used to represent JSON C<true> and C<false> in Perl strings.
  590. =head2 JSON::true
  591. Returns JSON true value which is blessed object.
  592. It C<isa> JSON::Boolean object.
  593. =head2 JSON::false
  594. Returns JSON false value which is blessed object.
  595. It C<isa> JSON::Boolean object.
  596. =head2 JSON::null
  597. Returns C<undef>.
  598. See L<MAPPING>, below, for more information on how JSON values are mapped to
  599. Perl.
  600. =head1 HOW DO I DECODE A DATA FROM OUTER AND ENCODE TO OUTER
  601. This section supposes that your perl vresion is 5.8 or later.
  602. If you know a JSON text from an outer world - a network, a file content, and so on,
  603. is encoded in UTF-8, you should use C<decode_json> or C<JSON> module object
  604. with C<utf8> enable. And the decoded result will contain UNICODE characters.
  605. # from network
  606. my $json = JSON->new->utf8;
  607. my $json_text = CGI->new->param( 'json_data' );
  608. my $perl_scalar = $json->decode( $json_text );
  609. # from file content
  610. local $/;
  611. open( my $fh, '<', 'json.data' );
  612. $json_text = <$fh>;
  613. $perl_scalar = decode_json( $json_text );
  614. If an outer data is not encoded in UTF-8, firstly you should C<decode> it.
  615. use Encode;
  616. local $/;
  617. open( my $fh, '<', 'json.data' );
  618. my $encoding = 'cp932';
  619. my $unicode_json_text = decode( $encoding, <$fh> ); # UNICODE
  620. # or you can write the below code.
  621. #
  622. # open( my $fh, "<:encoding($encoding)", 'json.data' );
  623. # $unicode_json_text = <$fh>;
  624. In this case, C<$unicode_json_text> is of course UNICODE string.
  625. So you B<cannot> use C<decode_json> nor C<JSON> module object with C<utf8> enable.
  626. Instead of them, you use C<JSON> module object with C<utf8> disable or C<from_json>.
  627. $perl_scalar = $json->utf8(0)->decode( $unicode_json_text );
  628. # or
  629. $perl_scalar = from_json( $unicode_json_text );
  630. Or C<encode 'utf8'> and C<decode_json>:
  631. $perl_scalar = decode_json( encode( 'utf8', $unicode_json_text ) );
  632. # this way is not efficient.
  633. And now, you want to convert your C<$perl_scalar> into JSON data and
  634. send it to an outer world - a network or a file content, and so on.
  635. Your data usually contains UNICODE strings and you want the converted data to be encoded
  636. in UTF-8, you should use C<encode_json> or C<JSON> module object with C<utf8> enable.
  637. print encode_json( $perl_scalar ); # to a network? file? or display?
  638. # or
  639. print $json->utf8->encode( $perl_scalar );
  640. If C<$perl_scalar> does not contain UNICODE but C<$encoding>-encoded strings
  641. for some reason, then its characters are regarded as B<latin1> for perl
  642. (because it does not concern with your $encoding).
  643. You B<cannot> use C<encode_json> nor C<JSON> module object with C<utf8> enable.
  644. Instead of them, you use C<JSON> module object with C<utf8> disable or C<to_json>.
  645. Note that the resulted text is a UNICODE string but no problem to print it.
  646. # $perl_scalar contains $encoding encoded string values
  647. $unicode_json_text = $json->utf8(0)->encode( $perl_scalar );
  648. # or
  649. $unicode_json_text = to_json( $perl_scalar );
  650. # $unicode_json_text consists of characters less than 0x100
  651. print $unicode_json_text;
  652. Or C<decode $encoding> all string values and C<encode_json>:
  653. $perl_scalar->{ foo } = decode( $encoding, $perl_scalar->{ foo } );
  654. # ... do it to each string values, then encode_json
  655. $json_text = encode_json( $perl_scalar );
  656. This method is a proper way but probably not efficient.
  657. See to L<Encode>, L<perluniintro>.
  658. =head1 COMMON OBJECT-ORIENTED INTERFACE
  659. =head2 new
  660. $json = new JSON
  661. Returns a new C<JSON> object inherited from either JSON::XS or JSON::PP
  662. that can be used to de/encode JSON strings.
  663. All boolean flags described below are by default I<disabled>.
  664. The mutators for flags all return the JSON object again and thus calls can
  665. be chained:
  666. my $json = JSON->new->utf8->space_after->encode({a => [1,2]})
  667. => {"a": [1, 2]}
  668. =head2 ascii
  669. $json = $json->ascii([$enable])
  670. $enabled = $json->get_ascii
  671. If $enable is true (or missing), then the encode method will not generate characters outside
  672. the code range 0..127. Any Unicode characters outside that range will be escaped using either
  673. a single \uXXXX or a double \uHHHH\uLLLLL escape sequence, as per RFC4627.
  674. If $enable is false, then the encode method will not escape Unicode characters unless
  675. required by the JSON syntax or other flags. This results in a faster and more compact format.
  676. This feature depends on the used Perl version and environment.
  677. See to L<JSON::PP/UNICODE HANDLING ON PERLS> if the backend is PP.
  678. JSON->new->ascii(1)->encode([chr 0x10401])
  679. => ["\ud801\udc01"]
  680. =head2 latin1
  681. $json = $json->latin1([$enable])
  682. $enabled = $json->get_latin1
  683. If $enable is true (or missing), then the encode method will encode the resulting JSON
  684. text as latin1 (or iso-8859-1), escaping any characters outside the code range 0..255.
  685. If $enable is false, then the encode method will not escape Unicode characters
  686. unless required by the JSON syntax or other flags.
  687. JSON->new->latin1->encode (["\x{89}\x{abc}"]
  688. => ["\x{89}\\u0abc"] # (perl syntax, U+abc escaped, U+89 not)
  689. =head2 utf8
  690. $json = $json->utf8([$enable])
  691. $enabled = $json->get_utf8
  692. If $enable is true (or missing), then the encode method will encode the JSON result
  693. into UTF-8, as required by many protocols, while the decode method expects to be handled
  694. an UTF-8-encoded string. Please note that UTF-8-encoded strings do not contain any
  695. characters outside the range 0..255, they are thus useful for bytewise/binary I/O.
  696. In future versions, enabling this option might enable autodetection of the UTF-16 and UTF-32
  697. encoding families, as described in RFC4627.
  698. If $enable is false, then the encode method will return the JSON string as a (non-encoded)
  699. Unicode string, while decode expects thus a Unicode string. Any decoding or encoding
  700. (e.g. to UTF-8 or UTF-16) needs to be done yourself, e.g. using the Encode module.
  701. Example, output UTF-16BE-encoded JSON:
  702. use Encode;
  703. $jsontext = encode "UTF-16BE", JSON::XS->new->encode ($object);
  704. Example, decode UTF-32LE-encoded JSON:
  705. use Encode;
  706. $object = JSON::XS->new->decode (decode "UTF-32LE", $jsontext);
  707. See to L<JSON::PP/UNICODE HANDLING ON PERLS> if the backend is PP.
  708. =head2 pretty
  709. $json = $json->pretty([$enable])
  710. This enables (or disables) all of the C<indent>, C<space_before> and
  711. C<space_after> (and in the future possibly more) flags in one call to
  712. generate the most readable (or most compact) form possible.
  713. Equivalent to:
  714. $json->indent->space_before->space_after
  715. The indent space length is three and JSON::XS cannot change the indent
  716. space length.
  717. =head2 indent
  718. $json = $json->indent([$enable])
  719. $enabled = $json->get_indent
  720. If C<$enable> is true (or missing), then the C<encode> method will use a multiline
  721. format as output, putting every array member or object/hash key-value pair
  722. into its own line, identing them properly.
  723. If C<$enable> is false, no newlines or indenting will be produced, and the
  724. resulting JSON text is guarenteed not to contain any C<newlines>.
  725. This setting has no effect when decoding JSON texts.
  726. The indent space length is three.
  727. With JSON::PP, you can also access C<indent_length> to change indent space length.
  728. =head2 space_before
  729. $json = $json->space_before([$enable])
  730. $enabled = $json->get_space_before
  731. If C<$enable> is true (or missing), then the C<encode> method will add an extra
  732. optional space before the C<:> separating keys from values in JSON objects.
  733. If C<$enable> is false, then the C<encode> method will not add any extra
  734. space at those places.
  735. This setting has no effect when decoding JSON texts.
  736. Example, space_before enabled, space_after and indent disabled:
  737. {"key" :"value"}
  738. =head2 space_after
  739. $json = $json->space_after([$enable])
  740. $enabled = $json->get_space_after
  741. If C<$enable> is true (or missing), then the C<encode> method will add an extra
  742. optional space after the C<:> separating keys from values in JSON objects
  743. and extra whitespace after the C<,> separating key-value pairs and array
  744. members.
  745. If C<$enable> is false, then the C<encode> method will not add any extra
  746. space at those places.
  747. This setting has no effect when decoding JSON texts.
  748. Example, space_before and indent disabled, space_after enabled:
  749. {"key": "value"}
  750. =head2 relaxed
  751. $json = $json->relaxed([$enable])
  752. $enabled = $json->get_relaxed
  753. If C<$enable> is true (or missing), then C<decode> will accept some
  754. extensions to normal JSON syntax (see below). C<encode> will not be
  755. affected in anyway. I<Be aware that this option makes you accept invalid
  756. JSON texts as if they were valid!>. I suggest only to use this option to
  757. parse application-specific files written by humans (configuration files,
  758. resource files etc.)
  759. If C<$enable> is false (the default), then C<decode> will only accept
  760. valid JSON texts.
  761. Currently accepted extensions are:
  762. =over 4
  763. =item * list items can have an end-comma
  764. JSON I<separates> array elements and key-value pairs with commas. This
  765. can be annoying if you write JSON texts manually and want to be able to
  766. quickly append elements, so this extension accepts comma at the end of
  767. such items not just between them:
  768. [
  769. 1,
  770. 2, <- this comma not normally allowed
  771. ]
  772. {
  773. "k1": "v1",
  774. "k2": "v2", <- this comma not normally allowed
  775. }
  776. =item * shell-style '#'-comments
  777. Whenever JSON allows whitespace, shell-style comments are additionally
  778. allowed. They are terminated by the first carriage-return or line-feed
  779. character, after which more white-space and comments are allowed.
  780. [
  781. 1, # this comment not allowed in JSON
  782. # neither this one...
  783. ]
  784. =back
  785. =head2 canonical
  786. $json = $json->canonical([$enable])
  787. $enabled = $json->get_canonical
  788. If C<$enable> is true (or missing), then the C<encode> method will output JSON objects
  789. by sorting their keys. This is adding a comparatively high overhead.
  790. If C<$enable> is false, then the C<encode> method will output key-value
  791. pairs in the order Perl stores them (which will likely change between runs
  792. of the same script).
  793. This option is useful if you want the same data structure to be encoded as
  794. the same JSON text (given the same overall settings). If it is disabled,
  795. the same hash might be encoded differently even if contains the same data,
  796. as key-value pairs have no inherent ordering in Perl.
  797. This setting has no effect when decoding JSON texts.
  798. =head2 allow_nonref
  799. $json = $json->allow_nonref([$enable])
  800. $enabled = $json->get_allow_nonref
  801. If C<$enable> is true (or missing), then the C<encode> method can convert a
  802. non-reference into its corresponding string, number or null JSON value,
  803. which is an extension to RFC4627. Likewise, C<decode> will accept those JSON
  804. values instead of croaking.
  805. If C<$enable> is false, then the C<encode> method will croak if it isn't
  806. passed an arrayref or hashref, as JSON texts must either be an object
  807. or array. Likewise, C<decode> will croak if given something that is not a
  808. JSON object or array.
  809. JSON->new->allow_nonref->encode ("Hello, World!")
  810. => "Hello, World!"
  811. =head2 allow_unknown
  812. $json = $json->allow_unknown ([$enable])
  813. $enabled = $json->get_allow_unknown
  814. If $enable is true (or missing), then "encode" will *not* throw an
  815. exception when it encounters values it cannot represent in JSON (for
  816. example, filehandles) but instead will encode a JSON "null" value.
  817. Note that blessed objects are not included here and are handled
  818. separately by c<allow_nonref>.
  819. If $enable is false (the default), then "encode" will throw an
  820. exception when it encounters anything it cannot encode as JSON.
  821. This option does not affect "decode" in any way, and it is
  822. recommended to leave it off unless you know your communications
  823. partner.
  824. =head2 allow_blessed
  825. $json = $json->allow_blessed([$enable])
  826. $enabled = $json->get_allow_blessed
  827. If C<$enable> is true (or missing), then the C<encode> method will not
  828. barf when it encounters a blessed reference. Instead, the value of the
  829. B<convert_blessed> option will decide whether C<null> (C<convert_blessed>
  830. disabled or no C<TO_JSON> method found) or a representation of the
  831. object (C<convert_blessed> enabled and C<TO_JSON> method found) is being
  832. encoded. Has no effect on C<decode>.
  833. If C<$enable> is false (the default), then C<encode> will throw an
  834. exception when it encounters a blessed object.
  835. =head2 convert_blessed
  836. $json = $json->convert_blessed([$enable])
  837. $enabled = $json->get_convert_blessed
  838. If C<$enable> is true (or missing), then C<encode>, upon encountering a
  839. blessed object, will check for the availability of the C<TO_JSON> method
  840. on the object's class. If found, it will be called in scalar context
  841. and the resulting scalar will be encoded instead of the object. If no
  842. C<TO_JSON> method is found, the value of C<allow_blessed> will decide what
  843. to do.
  844. The C<TO_JSON> method may safely call die if it wants. If C<TO_JSON>
  845. returns other blessed objects, those will be handled in the same
  846. way. C<TO_JSON> must take care of not causing an endless recursion cycle
  847. (== crash) in this case. The name of C<TO_JSON> was chosen because other
  848. methods called by the Perl core (== not by the user of the object) are
  849. usually in upper case letters and to avoid collisions with the C<to_json>
  850. function or method.
  851. This setting does not yet influence C<decode> in any way.
  852. If C<$enable> is false, then the C<allow_blessed> setting will decide what
  853. to do when a blessed object is found.
  854. =over
  855. =item convert_blessed_universally mode
  856. If use C<JSON> with C<-convert_blessed_universally>, the C<UNIVERSAL::TO_JSON>
  857. subroutine is defined as the below code:
  858. *UNIVERSAL::TO_JSON = sub {
  859. my $b_obj = B::svref_2object( $_[0] );
  860. return $b_obj->isa('B::HV') ? { %{ $_[0] } }
  861. : $b_obj->isa('B::AV') ? [ @{ $_[0] } ]
  862. : undef
  863. ;
  864. }
  865. This will cause that C<encode> method converts simple blessed objects into
  866. JSON objects as non-blessed object.
  867. JSON -convert_blessed_universally;
  868. $json->allow_blessed->convert_blessed->encode( $blessed_object )
  869. This feature is experimental and may be removed in the future.
  870. =back
  871. =head2 filter_json_object
  872. $json = $json->filter_json_object([$coderef])
  873. When C<$coderef> is specified, it will be called from C<decode> each
  874. time it decodes a JSON object. The only argument passed to the coderef
  875. is a reference to the newly-created hash. If the code references returns
  876. a single scalar (which need not be a reference), this value
  877. (i.e. a copy of that scalar to avoid aliasing) is inserted into the
  878. deserialised data structure. If it returns an empty list
  879. (NOTE: I<not> C<undef>, which is a valid scalar), the original deserialised
  880. hash will be inserted. This setting can slow down decoding considerably.
  881. When C<$coderef> is omitted or undefined, any existing callback will
  882. be removed and C<decode> will not change the deserialised hash in any
  883. way.
  884. Example, convert all JSON objects into the integer 5:
  885. my $js = JSON->new->filter_json_object (sub { 5 });
  886. # returns [5]
  887. $js->decode ('[{}]'); # the given subroutine takes a hash reference.
  888. # throw an exception because allow_nonref is not enabled
  889. # so a lone 5 is not allowed.
  890. $js->decode ('{"a":1, "b":2}');
  891. =head2 filter_json_single_key_object
  892. $json = $json->filter_json_single_key_object($key [=> $coderef])
  893. Works remotely similar to C<filter_json_object>, but is only called for
  894. JSON objects having a single key named C<$key>.
  895. This C<$coderef> is called before the one specified via
  896. C<filter_json_object>, if any. It gets passed the single value in the JSON
  897. object. If it returns a single value, it will be inserted into the data
  898. structure. If it returns nothing (not even C<undef> but the empty list),
  899. the callback from C<filter_json_object> will be called next, as if no
  900. single-key callback were specified.
  901. If C<$coderef> is omitted or undefined, the corresponding callback will be
  902. disabled. There can only ever be one callback for a given key.
  903. As this callback gets called less often then the C<filter_json_object>
  904. one, decoding speed will not usually suffer as much. Therefore, single-key
  905. objects make excellent targets to serialise Perl objects into, especially
  906. as single-key JSON objects are as close to the type-tagged value concept
  907. as JSON gets (it's basically an ID/VALUE tuple). Of course, JSON does not
  908. support this in any way, so you need to make sure your data never looks
  909. like a serialised Perl hash.
  910. Typical names for the single object key are C<__class_whatever__>, or
  911. C<$__dollars_are_rarely_used__$> or C<}ugly_brace_placement>, or even
  912. things like C<__class_md5sum(classname)__>, to reduce the risk of clashing
  913. with real hashes.
  914. Example, decode JSON objects of the form C<< { "__widget__" => <id> } >>
  915. into the corresponding C<< $WIDGET{<id>} >> object:
  916. # return whatever is in $WIDGET{5}:
  917. JSON
  918. ->new
  919. ->filter_json_single_key_object (__widget__ => sub {
  920. $WIDGET{ $_[0] }
  921. })
  922. ->decode ('{"__widget__": 5')
  923. # this can be used with a TO_JSON method in some "widget" class
  924. # for serialisation to json:
  925. sub WidgetBase::TO_JSON {
  926. my ($self) = @_;
  927. unless ($self->{id}) {
  928. $self->{id} = ..get..some..id..;
  929. $WIDGET{$self->{id}} = $self;
  930. }
  931. { __widget__ => $self->{id} }
  932. }
  933. =head2 shrink
  934. $json = $json->shrink([$enable])
  935. $enabled = $json->get_shrink
  936. With JSON::XS, this flag resizes strings generated by either
  937. C<encode> or C<decode> to their minimum size possible. This can save
  938. memory when your JSON texts are either very very long or you have many
  939. short strings. It will also try to downgrade any strings to octet-form
  940. if possible: perl stores strings internally either in an encoding called
  941. UTF-X or in octet-form. The latter cannot store everything but uses less
  942. space in general (and some buggy Perl or C code might even rely on that
  943. internal representation being used).
  944. With JSON::PP, it is noop about resizing strings but tries
  945. C<utf8::downgrade> to the returned string by C<encode>. See to L<utf8>.
  946. See to L<JSON::XS/OBJECT-ORIENTED INTERFACE> and L<JSON::PP/METHODS>.
  947. =head2 max_depth
  948. $json = $json->max_depth([$maximum_nesting_depth])
  949. $max_depth = $json->get_max_depth
  950. Sets the maximum nesting level (default C<512>) accepted while encoding
  951. or decoding. If a higher nesting level is detected in JSON text or a Perl
  952. data structure, then the encoder and decoder will stop and croak at that
  953. point.
  954. Nesting level is defined by number of hash- or arrayrefs that the encoder
  955. needs to traverse to reach a given point or the number of C<{> or C<[>
  956. characters without their matching closing parenthesis crossed to reach a
  957. given character in a string.
  958. If no argument is given, the highest possible setting will be used, which
  959. is rarely useful.
  960. Note that nesting is implemented by recursion in C. The default value has
  961. been chosen to be as large as typical operating systems allow without
  962. crashing. (JSON::XS)
  963. With JSON::PP as the backend, when a large value (100 or more) was set and
  964. it de/encodes a deep nested object/text, it may raise a warning
  965. 'Deep recursion on subroutin' at the perl runtime phase.
  966. See L<JSON::XS/SECURITY CONSIDERATIONS> for more info on why this is useful.
  967. =head2 max_size
  968. $json = $json->max_size([$maximum_string_size])
  969. $max_size = $json->get_max_size
  970. Set the maximum length a JSON text may have (in bytes) where decoding is
  971. being attempted. The default is C<0>, meaning no limit. When C<decode>
  972. is called on a string that is longer then this many bytes, it will not
  973. attempt to decode the string but throw an exception. This setting has no
  974. effect on C<encode> (yet).
  975. If no argument is given, the limit check will be deactivated (same as when
  976. C<0> is specified).
  977. See L<JSON::XS/SECURITY CONSIDERATIONS>, below, for more info on why this is useful.
  978. =head2 encode
  979. $json_text = $json->encode($perl_scalar)
  980. Converts the given Perl data structure (a simple scalar or a reference
  981. to a hash or array) to its JSON representation. Simple scalars will be
  982. converted into JSON string or number sequences, while references to arrays
  983. become JSON arrays and references to hashes become JSON objects. Undefined
  984. Perl values (e.g. C<undef>) become JSON C<null> values.
  985. References to the integers C<0> and C<1> are converted into C<true> and C<false>.
  986. =head2 decode
  987. $perl_scalar = $json->decode($json_text)
  988. The opposite of C<encode>: expects a JSON text and tries to parse it,
  989. returning the resulting simple scalar or reference. Croaks on error.
  990. JSON numbers and strings become simple Perl scalars. JSON arrays become
  991. Perl arrayrefs and JSON objects become Perl hashrefs. C<true> becomes
  992. C<1> (C<JSON::true>), C<false> becomes C<0> (C<JSON::false>) and
  993. C<null> becomes C<undef>.
  994. =head2 decode_prefix
  995. ($perl_scalar, $characters) = $json->decode_prefix($json_text)
  996. This works like the C<decode> method, but instead of raising an exception
  997. when there is trailing garbage after the first JSON object, it will
  998. silently stop parsing there and return the number of characters consumed
  999. so far.
  1000. JSON->new->decode_prefix ("[1] the tail")
  1001. => ([], 3)
  1002. See to L<JSON::XS/OBJECT-ORIENTED INTERFACE>
  1003. =head2 property
  1004. $boolean = $json->property($property_name)
  1005. Returns a boolean value about above some properties.
  1006. The available properties are C<ascii>, C<latin1>, C<utf8>,
  1007. C<indent>,C<space_before>, C<space_after>, C<relaxed>, C<canonical>,
  1008. C<allow_nonref>, C<allow_unknown>, C<allow_blessed>, C<convert_blessed>,
  1009. C<shrink>, C<max_depth> and C<max_size>.
  1010. $boolean = $json->property('utf8');
  1011. => 0
  1012. $json->utf8;
  1013. $boolean = $json->property('utf8');
  1014. => 1
  1015. Sets the property with a given boolean value.
  1016. $json = $json->property($property_name => $boolean);
  1017. With no argumnt, it returns all the above properties as a hash reference.
  1018. $flag_hashref = $json->property();
  1019. =head1 INCREMENTAL PARSING
  1020. Most of this section are copied and modified from L<JSON::XS/INCREMENTAL PARSING>.
  1021. In some cases, there is the need for incremental parsing of JSON texts.
  1022. This module does allow you to parse a JSON stream incrementally.
  1023. It does so by accumulating text until it has a full JSON object, which
  1024. it then can decode. This process is similar to using C<decode_prefix>
  1025. to see if a full JSON object is available, but is much more efficient
  1026. (and can be implemented with a minimum of method calls).
  1027. The backend module will only attempt to parse the JSON text once it is sure it
  1028. has enough text to get a decisive result, using a very simple but
  1029. truly incremental parser. This means that it sometimes won't stop as
  1030. early as the full parser, for example, it doesn't detect parenthese
  1031. mismatches. The only thing it guarantees is that it starts decoding as
  1032. soon as a syntactically valid JSON text has been seen. This means you need
  1033. to set resource limits (e.g. C<max_size>) to ensure the parser will stop
  1034. parsing in the presence if syntax errors.
  1035. The following methods implement this incremental parser.
  1036. =head2 incr_parse
  1037. $json->incr_parse( [$string] ) # void context
  1038. $obj_or_undef = $json->incr_parse( [$string] ) # scalar context
  1039. @obj_or_empty = $json->incr_parse( [$string] ) # list context
  1040. This is the central parsing function. It can both append new text and
  1041. extract objects from the stream accumulated so far (both of these
  1042. functions are optional).
  1043. If C<$string> is given, then this string is appended to the already
  1044. existing JSON fragment stored in the C<$json> object.
  1045. After that, if the function is called in void context, it will simply
  1046. return without doing anything further. This can be used to add more text
  1047. in as many chunks as you want.
  1048. If the method is called in scalar context, then it will try to extract
  1049. exactly I<one> JSON object. If that is successful, it will return this
  1050. object, otherwise it will return C<undef>. If there is a parse error,
  1051. this method will croak just as C<decode> would do (one can then use
  1052. C<incr_skip> to skip the errornous part). This is the most common way of
  1053. using the method.
  1054. And finally, in list context, it will try to extract as many objects
  1055. from the stream as it can find and return them, or the empty list
  1056. otherwise. For this to work, there must be no separators between the JSON
  1057. objects or arrays, instead they must be concatenated back-to-back. If
  1058. an error occurs, an exception will be raised as in the scalar context
  1059. case. Note that in this case, any previously-parsed JSON texts will be
  1060. lost.
  1061. Example: Parse some JSON arrays/objects in a given string and return them.
  1062. my @objs = JSON->new->incr_parse ("[5][7][1,2]");
  1063. =head2 incr_text
  1064. $lvalue_string = $json->incr_text
  1065. This method returns the currently stored JSON fragment as an lvalue, that
  1066. is, you can manipulate it. This I<only> works when a preceding call to
  1067. C<incr_parse> in I<scalar context> successfully returned an object. Under
  1068. all other circumstances you must not call this function (I mean it.
  1069. although in simple tests it might actually work, it I<will> fail under
  1070. real world conditions). As a special exception, you can also call this
  1071. method before having parsed anything.
  1072. This function is useful in two cases: a) finding the trailing text after a
  1073. JSON object or b) parsing multiple JSON objects separated by non-JSON text
  1074. (such as commas).
  1075. $json->incr_text =~ s/\s*,\s*//;
  1076. In Perl 5.005, C<lvalue> attribute is not available.
  1077. You must write codes like the below:
  1078. $string = $json->incr_text;
  1079. $string =~ s/\s*,\s*//;
  1080. $json->incr_text( $string );
  1081. =head2 incr_skip
  1082. $json->incr_skip
  1083. This will reset the state of the incremental parser and will remove the
  1084. parsed text from the input buffer. This is useful after C<incr_parse>
  1085. died, in which case the input buffer and incremental parser state is left
  1086. unchanged, to skip the text parsed so far and to reset the parse state.
  1087. =head2 incr_reset
  1088. $json->incr_reset
  1089. This completely resets the incremental parser, that is, after this call,
  1090. it will be as if the parser had never parsed anything.
  1091. This is useful if you want ot repeatedly parse JSON objects and want to
  1092. ignore any trailing data, which means you have to reset the parser after
  1093. each successful decode.
  1094. See to L<JSON::XS/INCREMENTAL PARSING> for examples.
  1095. =head1 JSON::PP SUPPORT METHODS
  1096. The below methods are JSON::PP own methods, so when C<JSON> works
  1097. with JSON::PP (i.e. the created object is a JSON::PP object), available.
  1098. See to L<JSON::PP/JSON::PP OWN METHODS> in detail.
  1099. If you use C<JSON> with additonal C<-support_by_pp>, some methods
  1100. are available even with JSON::XS. See to L<USE PP FEATURES EVEN THOUGH XS BACKEND>.
  1101. BEING { $ENV{PERL_JSON_BACKEND} = 'JSON::XS' }
  1102. use JSON -support_by_pp;
  1103. my $json = new JSON;
  1104. $json->allow_nonref->escape_slash->encode("/");
  1105. # functional interfaces too.
  1106. print to_json(["/"], {escape_slash => 1});
  1107. print from_json('["foo"]', {utf8 => 1});
  1108. If you do not want to all functions but C<-support_by_pp>,
  1109. use C<-no_export>.
  1110. use JSON -support_by_pp, -no_export;
  1111. # functional interfaces are not exported.
  1112. =head2 allow_singlequote
  1113. $json = $json->allow_singlequote([$enable])
  1114. If C<$enable> is true (or missing), then C<decode> will accept
  1115. any JSON strings quoted by single quotations that are invalid JSON
  1116. format.
  1117. $json->allow_singlequote->decode({"foo":'bar'});
  1118. $json->allow_singlequote->decode({'foo':"bar"});
  1119. $json->allow_singlequote->decode({'foo':'bar'});
  1120. As same as the C<relaxed> option, this option may be used to parse
  1121. application-specific files written by humans.
  1122. =head2 allow_barekey
  1123. $json = $json->allow_barekey([$enable])
  1124. If C<$enable> is true (or missing), then C<decode> will accept
  1125. bare keys of JSON object that are invalid JSON format.
  1126. As same as the C<relaxed> option, this option may be used to parse
  1127. application-specific files written by humans.
  1128. $json->allow_barekey->decode('{foo:"bar"}');
  1129. =head2 allow_bignum
  1130. $json = $json->allow_bignum([$enable])
  1131. If C<$enable> is true (or missing), then C<decode> will convert
  1132. the big integer Perl cannot handle as integer into a L<Math::BigInt>
  1133. object and convert a floating number (any) into a L<Math::BigFloat>.
  1134. On the contary, C<encode> converts C<Math::BigInt> objects and C<Math::BigFloat>
  1135. objects into JSON numbers with C<allow_blessed> enable.
  1136. $json->allow_nonref->allow_blessed->allow_bignum;
  1137. $bigfloat = $json->decode('2.000000000000000000000000001');
  1138. print $json->encode($bigfloat);
  1139. # => 2.000000000000000000000000001
  1140. See to L<MAPPING> aboout the conversion of JSON number.
  1141. =head2 loose
  1142. $json = $json->loose([$enable])
  1143. The unescaped [\x00-\x1f\x22\x2f\x5c] strings are invalid in JSON strings
  1144. and the module doesn't allow to C<decode> to these (except for \x2f).
  1145. If C<$enable> is true (or missing), then C<decode> will accept these
  1146. unescaped strings.
  1147. $json->loose->decode(qq|["abc
  1148. def"]|);
  1149. See to L<JSON::PP/JSON::PP OWN METHODS>.
  1150. =head2 escape_slash
  1151. $json = $json->escape_slash([$enable])
  1152. According to JSON Grammar, I<slash> (U+002F) is escaped. But by default
  1153. JSON backend modules encode strings without escaping slash.
  1154. If C<$enable> is true (or missing), then C<encode> will escape slashes.
  1155. =head2 indent_length
  1156. $json = $json->indent_length($length)
  1157. With JSON::XS, The indent space length is 3 and cannot be changed.
  1158. With JSON::PP, it sets the indent space length with the given $length.
  1159. The default is 3. The acceptable range is 0 to 15.
  1160. =head2 sort_by
  1161. $json = $json->sort_by($function_name)
  1162. $json = $json->sort_by($subroutine_ref)
  1163. If $function_name or $subroutine_ref are set, its sort routine are used.
  1164. $js = $pc->sort_by(sub { $JSON::PP::a cmp $JSON::PP::b })->encode($obj);
  1165. # is($js, q|{"a":1,"b":2,"c":3,"d":4,"e":5,"f":6,"g":7,"h":8,"i":9}|);
  1166. $js = $pc->sort_by('own_sort')->encode($obj);
  1167. # is($js, q|{"a":1,"b":2,"c":3,"d":4,"e":5,"f":6,"g":7,"h":8,"i":9}|);
  1168. sub JSON::PP::own_sort { $JSON::PP::a cmp $JSON::PP::b }
  1169. As the sorting routine runs in the JSON::PP scope, the given
  1170. subroutine name and the special variables C<$a>, C<$b> will begin
  1171. with 'JSON::PP::'.
  1172. If $integer is set, then the effect is same as C<canonical> on.
  1173. See to L<JSON::PP/JSON::PP OWN METHODS>.
  1174. =head1 MAPPING
  1175. This section is copied from JSON::XS and modified to C<JSON>.
  1176. JSON::XS and JSON::PP mapping mechanisms are almost equivalent.
  1177. See to L<JSON::XS/MAPPING>.
  1178. =head2 JSON -> PERL
  1179. =over 4
  1180. =item object
  1181. A JSON object becomes a reference to a hash in Perl. No ordering of object
  1182. keys is preserved (JSON does not preserver object key ordering itself).
  1183. =item array
  1184. A JSON array becomes a reference to an array in Perl.
  1185. =item string
  1186. A JSON string becomes a string scalar in Perl - Unicode codepoints in JSON
  1187. are represented by the same codepoints in the Perl string, so no manual
  1188. decoding is necessary.
  1189. =item number
  1190. A JSON number becomes either an integer, numeric (floating point) or
  1191. string scalar in perl, depending on its range and any fractional parts. On
  1192. the Perl level, there is no difference between those as Perl handles all
  1193. the conversion details, but an integer may take slightly less memory and
  1194. might represent more values exactly than floating point numbers.
  1195. If the number consists of digits only, C<JSON> will try to represent
  1196. it as an integer value. If that fails, it will try to represent it as
  1197. a numeric (floating point) value if that is possible without loss of
  1198. precision. Otherwise it will preserve the number as a string value (in
  1199. which case you lose roundtripping ability, as the JSON number will be
  1200. re-encoded toa JSON string).
  1201. Numbers containing a fractional or exponential part will always be
  1202. represented as numeric (floating point) values, possibly at a loss of
  1203. precision (in which case you might lose perfect roundtripping ability, but
  1204. the JSON number will still be re-encoded as a JSON number).
  1205. Note that precision is not accuracy - binary floating point values cannot
  1206. represent most decimal fractions exactly, and when converting from and to
  1207. floating point, C<JSON> only guarantees precision up to but not including
  1208. the leats significant bit.
  1209. If the backend is JSON::PP and C<allow_bignum> is enable, the big integers
  1210. and the numeric can be optionally converted into L<Math::BigInt> and
  1211. L<Math::BigFloat> objects.
  1212. =item true, false
  1213. These JSON atoms become C<JSON::true> and C<JSON::false>,
  1214. respectively. They are overloaded to act almost exactly like the numbers
  1215. C<1> and C<0>. You can check wether a scalar is a JSON boolean by using
  1216. the C<JSON::is_bool> function.
  1217. If C<JSON::true> and C<JSON::false> are used as strings or compared as strings,
  1218. they represent as C<true> and C<false> respectively.
  1219. print JSON::true . "\n";
  1220. => true
  1221. print JSON::true + 1;
  1222. => 1
  1223. ok(JSON::true eq 'true');
  1224. ok(JSON::true eq '1');
  1225. ok(JSON::true == 1);
  1226. C<JSON> will install these missing overloading features to the backend modules.
  1227. =item null
  1228. A JSON null atom becomes C<undef> in Perl.
  1229. C<JSON::null> returns C<unddef>.
  1230. =back
  1231. =head2 PERL -> JSON
  1232. The mapping from Perl to JSON is slightly more difficult, as Perl is a
  1233. truly typeless language, so we can only guess which JSON type is meant by
  1234. a Perl value.
  1235. =over 4
  1236. =item hash references
  1237. Perl hash references become JSON objects. As there is no inherent ordering
  1238. in hash keys (or JSON objects), they will usually be encoded in a
  1239. pseudo-random order that can change between runs of the same program but
  1240. stays generally the same within a single run of a program. C<JSON>
  1241. optionally sort the hash keys (determined by the I<canonical> flag), so
  1242. the same datastructure will serialise to the same JSON text (given same
  1243. settings and version of JSON::XS), but this incurs a runtime overhead
  1244. and is only rarely useful, e.g. when you want to compare some JSON text
  1245. against another for equality.
  1246. In future, the ordered object feature will be added to JSON::PP using C<tie> mechanism.
  1247. =item array references
  1248. Perl array references become JSON arrays.
  1249. =item other references
  1250. Other unblessed references are generally not allowed and will cause an
  1251. exception to be thrown, except for references to the integers C<0> and
  1252. C<1>, which get turned into C<false> and C<true> atoms in JSON. You can
  1253. also use C<JSON::false> and C<JSON::true> to improve readability.
  1254. to_json [\0,JSON::true] # yields [false,true]
  1255. =item JSON::true, JSON::false, JSON::null
  1256. These special values become JSON true and JSON false values,
  1257. respectively. You can also use C<\1> and C<\0> directly if you want.
  1258. JSON::null returns C<undef>.
  1259. =item blessed objects
  1260. Blessed objects are not directly representable in JSON. See the
  1261. C<allow_blessed> and C<convert_blessed> methods on various options on
  1262. how to deal with this: basically, you can choose between throwing an
  1263. exception, encoding the reference as if it weren't blessed, or provide
  1264. your own serialiser method.
  1265. With C<convert_blessed_universally> mode, C<encode> converts blessed
  1266. hash references or blessed array references (contains other blessed references)
  1267. into JSON members and arrays.
  1268. use JSON -convert_blessed_universally;
  1269. JSON->new->allow_blessed->convert_blessed->encode( $blessed_object );
  1270. See to L<convert_blessed>.
  1271. =item simple scalars
  1272. Simple Perl scalars (any scalar that is not a reference) are the most
  1273. difficult objects to encode: JSON::XS and JSON::PP will encode undefined scalars as
  1274. JSON C<null> values, scalars that have last been used in a string context
  1275. before encoding as JSON strings, and anything else as number value:
  1276. # dump as number
  1277. encode_json [2] # yields [2]
  1278. encode_json [-3.0e17] # yields [-3e+17]
  1279. my $value = 5; encode_json [$value] # yields [5]
  1280. # used as string, so dump as string
  1281. print $value;
  1282. encode_json [$value] # yields ["5"]
  1283. # undef becomes null
  1284. encode_json [undef] # yields [null]
  1285. You can force the type to be a string by stringifying it:
  1286. my $x = 3.1; # some variable containing a number
  1287. "$x"; # stringified
  1288. $x .= ""; # another, more awkward way to stringify
  1289. print $x; # perl does it for you, too, quite often
  1290. You can force the type to be a number by numifying it:
  1291. my $x = "3"; # some variable containing a string
  1292. $x += 0; # numify it, ensuring it will be dumped as a number
  1293. $x *= 1; # same thing, the choise is yours.
  1294. You can not currently force the type in other, less obscure, ways.
  1295. Note that numerical precision has the same meaning as under Perl (so
  1296. binary to decimal conversion follows the same rules as in Perl, which
  1297. can differ to other languages). Also, your perl interpreter might expose
  1298. extensions to the floating point numbers of your platform, such as
  1299. infinities or NaN's - these cannot be represented in JSON, and it is an
  1300. error to pass those in.
  1301. =item Big Number
  1302. If the backend is JSON::PP and C<allow_bignum> is enable,
  1303. C<encode> converts C<Math::BigInt> objects and C<Math::BigFloat>
  1304. objects into JSON numbers.
  1305. =back
  1306. =head1 JSON and ECMAscript
  1307. See to L<JSON::XS/JSON and ECMAscript>.
  1308. =head1 JSON and YAML
  1309. JSON is not a subset of YAML.
  1310. See to L<JSON::XS/JSON and YAML>.
  1311. =head1 BACKEND MODULE DECISION
  1312. When you use C<JSON>, C<JSON> tries to C<use> JSON::XS. If this call failed, it will
  1313. C<uses> JSON::PP. The required JSON::XS version is I<2.2> or later.
  1314. The C<JSON> constructor method returns an object inherited from the backend module,
  1315. and JSON::XS object is a blessed scaler reference while JSON::PP is a blessed hash
  1316. reference.
  1317. So, your program should not depend on the backend module, especially
  1318. returned objects should not be modified.
  1319. my $json = JSON->new; # XS or PP?
  1320. $json->{stash} = 'this is xs object'; # this code may raise an error!
  1321. To check the backend module, there are some methods - C<backend>, C<is_pp> and C<is_xs>.
  1322. JSON->backend; # 'JSON::XS' or 'JSON::PP'
  1323. JSON->backend->is_pp: # 0 or 1
  1324. JSON->backend->is_xs: # 1 or 0
  1325. $json->is_xs; # 1 or 0
  1326. $json->is_pp; # 0 or 1
  1327. If you set an enviornment variable C<PERL_JSON_BACKEND>, The calling action will be changed.
  1328. =over
  1329. =item PERL_JSON_BACKEND = 0 or PERL_JSON_BACKEND = 'JSON::PP'
  1330. Always use JSON::PP
  1331. =item PERL_JSON_BACKEND == 1 or PERL_JSON_BACKEND = 'JSON::XS,JSON::PP'
  1332. (The default) Use compiled JSON::XS if it is properly compiled & installed,
  1333. otherwise use JSON::PP.
  1334. =item PERL_JSON_BACKEND == 2 or PERL_JSON_BACKEND = 'JSON::XS'
  1335. Always use compiled JSON::XS, die if it isn't properly compiled & installed.
  1336. =item PERL_JSON_BACKEND = 'JSON::backportPP'
  1337. Always use JSON::backportPP.
  1338. JSON::backportPP is JSON::PP back port module.
  1339. C<JSON> includs JSON::backportPP instead of JSON::PP.
  1340. =back
  1341. These ideas come from L<DBI::PurePerl> mechanism.
  1342. example:
  1343. BEGIN { $ENV{PERL_JSON_BACKEND} = 'JSON::PP' }
  1344. use JSON; # always uses JSON::PP
  1345. In future, it may be able to specify another module.
  1346. =head1 USE PP FEATURES EVEN THOUGH XS BACKEND
  1347. Many methods are available with either JSON::XS or JSON::PP and
  1348. when the backend module is JSON::XS, if any JSON::PP specific (i.e. JSON::XS unspported)
  1349. method is called, it will C<warn> and be noop.
  1350. But If you C<use> C<JSON> passing the optional string C<-support_by_pp>,
  1351. it makes a part of those unupported methods available.
  1352. This feature is achieved by using JSON::PP in C<de/encode>.
  1353. BEGIN { $ENV{PERL_JSON_BACKEND} = 2 } # with JSON::XS
  1354. use JSON -support_by_pp;
  1355. my $json = new JSON;
  1356. $json->allow_nonref->escape_slash->encode("/");
  1357. At this time, the returned object is a C<JSON::Backend::XS::Supportable>
  1358. object (re-blessed XS object), and by checking JSON::XS unsupported flags
  1359. in de/encoding, can support some unsupported methods - C<loose>, C<allow_bignum>,
  1360. C<allow_barekey>, C<allow_singlequote>, C<escape_slash> and C<indent_length>.
  1361. When any unsupported methods are not enable, C<XS de/encode> will be
  1362. used as is. The switch is achieved by changing the symbolic tables.
  1363. C<-support_by_pp> is effective only when the backend module is JSON::XS
  1364. and it makes the de/encoding speed down a bit.
  1365. See to L<JSON::PP SUPPORT METHODS>.
  1366. =head1 INCOMPATIBLE CHANGES TO OLD VERSION
  1367. There are big incompatibility between new version (2.00) and old (1.xx).
  1368. If you use old C<JSON> 1.xx in your code, please check it.
  1369. See to L<Transition ways from 1.xx to 2.xx.>
  1370. =over
  1371. =item jsonToObj and objToJson are obsoleted.
  1372. Non Perl-style name C<jsonToObj> and C<objToJson> are obsoleted
  1373. (but not yet deleted from the source).
  1374. If you use these functions in your code, please replace them
  1375. with C<from_json> and C<to_json>.
  1376. =item Global variables are no longer available.
  1377. C<JSON> class variables - C<$JSON::AUTOCONVERT>, C<$JSON::BareKey>, etc...
  1378. - are not available any longer.
  1379. Instead, various features can be used through object methods.
  1380. =item Package JSON::Converter and JSON::Parser are deleted.
  1381. Now C<JSON> bundles with JSON::PP which can handle JSON more properly than them.
  1382. =item Package JSON::NotString is deleted.
  1383. There was C<JSON::NotString> class which represents JSON value C<true>, C<false>, C<null>
  1384. and numbers. It was deleted and replaced by C<JSON::Boolean>.
  1385. C<JSON::Boolean> represents C<true> and C<false>.
  1386. C<JSON::Boolean> does not represent C<null>.
  1387. C<JSON::null> returns C<undef>.
  1388. C<JSON> makes L<JSON::XS::Boolean> and L<JSON::PP::Boolean> is-a relation
  1389. to L<JSON::Boolean>.
  1390. =item function JSON::Number is obsoleted.
  1391. C<JSON::Number> is now needless because JSON::XS and JSON::PP have
  1392. round-trip integrity.
  1393. =item JSONRPC modules are deleted.
  1394. Perl implementation of JSON-RPC protocol - C<JSONRPC >, C<JSONRPC::Transport::HTTP>
  1395. and C<Apache::JSONRPC > are deleted in this distribution.
  1396. Instead of them, there is L<JSON::RPC> which supports JSON-RPC protocol version 1.1.
  1397. =back
  1398. =head2 Transition ways from 1.xx to 2.xx.
  1399. You should set C<suport_by_pp> mode firstly, because
  1400. it is always successful for the below codes even with JSON::XS.
  1401. use JSON -support_by_pp;
  1402. =over
  1403. =item Exported jsonToObj (simple)
  1404. from_json($json_text);
  1405. =item Exported objToJson (simple)
  1406. to_json($perl_scalar);
  1407. =item Exported jsonToObj (advanced)
  1408. $flags = {allow_barekey => 1, allow_singlequote => 1};
  1409. from_json($json_text, $flags);
  1410. equivalent to:
  1411. $JSON::BareKey = 1;
  1412. $JSON::QuotApos = 1;
  1413. jsonToObj($json_text);
  1414. =item Exported objToJson (advanced)
  1415. $flags = {allow_blessed => 1, allow_barekey => 1};
  1416. to_json($perl_scalar, $flags);
  1417. equivalent to:
  1418. $JSON::BareKey = 1;
  1419. objToJson($perl_scalar);
  1420. =item jsonToObj as object method
  1421. $json->decode($json_text);
  1422. =item objToJson as object method
  1423. $json->encode($perl_scalar);
  1424. =item new method with parameters
  1425. The C<new> method in 2.x takes any parameters no longer.
  1426. You can set parameters instead;
  1427. $json = JSON->new->pretty;
  1428. =item $JSON::Pretty, $JSON::Indent, $JSON::Delimiter
  1429. If C<indent> is enable, that means C<$JSON::Pretty> flag set. And
  1430. C<$JSON::Delimiter> was substituted by C<space_before> and C<space_after>.
  1431. In conclusion:
  1432. $json->indent->space_before->space_after;
  1433. Equivalent to:
  1434. $json->pretty;
  1435. To change indent length, use C<indent_length>.
  1436. (Only with JSON::PP, if C<-support_by_pp> is not used.)
  1437. $json->pretty->indent_length(2)->encode($perl_scalar);
  1438. =item $JSON::BareKey
  1439. (Only with JSON::PP, if C<-support_by_pp> is not used.)
  1440. $json->allow_barekey->decode($json_text)
  1441. =item $JSON::ConvBlessed
  1442. use C<-convert_blessed_universally>. See to L<convert_blessed>.
  1443. =item $JSON::QuotApos
  1444. (Only with JSON::PP, if C<-support_by_pp> is not used.)
  1445. $json->allow_singlequote->decode($json_text)
  1446. =item $JSON::SingleQuote
  1447. Disable. C<JSON> does not make such a invalid JSON string any longer.
  1448. =item $JSON::KeySort
  1449. $json->canonical->encode($perl_scalar)
  1450. This is the ascii sort.
  1451. If you want to use with your own sort routine, check the C<sort_by> method.
  1452. (Only with JSON::PP, even if C<-support_by_pp> is used currently.)
  1453. $json->sort_by($sort_routine_ref)->encode($perl_scalar)
  1454. $json->sort_by(sub { $JSON::PP::a <=> $JSON::PP::b })->encode($perl_scalar)
  1455. Can't access C<$a> and C<$b> but C<$JSON::PP::a> and C<$JSON::PP::b>.
  1456. =item $JSON::SkipInvalid
  1457. $json->allow_unknown
  1458. =item $JSON::AUTOCONVERT
  1459. Needless. C<JSON> backend modules have the round-trip integrity.
  1460. =item $JSON::UTF8
  1461. Needless because C<JSON> (JSON::XS/JSON::PP) sets
  1462. the UTF8 flag on properly.
  1463. # With UTF8-flagged strings
  1464. $json->allow_nonref;
  1465. $str = chr(1000); # UTF8-flagged
  1466. $json_text = $json->utf8(0)->encode($str);
  1467. utf8::is_utf8($json_text);
  1468. # true
  1469. $json_text = $json->utf8(1)->encode($str);
  1470. utf8::is_utf8($json_text);
  1471. # false
  1472. $str = '"' . chr(1000) . '"'; # UTF8-flagged
  1473. $perl_scalar = $json->utf8(0)->decode($str);
  1474. utf8::is_utf8($perl_scalar);
  1475. # true
  1476. $perl_scalar = $json->utf8(1)->decode($str);
  1477. # died because of 'Wide character in subroutine'
  1478. See to L<JSON::XS/A FEW NOTES ON UNICODE AND PERL>.
  1479. =item $JSON::UnMapping
  1480. Disable. See to L<MAPPING>.
  1481. =item $JSON::SelfConvert
  1482. This option was deleted.
  1483. Instead of it, if a givien blessed object has the C<TO_JSON> method,
  1484. C<TO_JSON> will be executed with C<convert_blessed>.
  1485. $json->convert_blessed->encode($bleesed_hashref_or_arrayref)
  1486. # if need, call allow_blessed
  1487. Note that it was C<toJson> in old version, but now not C<toJson> but C<TO_JSON>.
  1488. =back
  1489. =head1 TODO
  1490. =over
  1491. =item example programs
  1492. =back
  1493. =head1 THREADS
  1494. No test with JSON::PP. If with JSON::XS, See to L<JSON::XS/THREADS>.
  1495. =head1 BUGS
  1496. Please report bugs relevant to C<JSON> to E<lt>makamaka[at]cpan.orgE<gt>.
  1497. =head1 SEE ALSO
  1498. Most of the document is copied and modified from JSON::XS doc.
  1499. L<JSON::XS>, L<JSON::PP>
  1500. C<RFC4627>(L<http://www.ietf.org/rfc/rfc4627.txt>)
  1501. =head1 AUTHOR
  1502. Makamaka Hannyaharamitu, E<lt>makamaka[at]cpan.orgE<gt>
  1503. JSON::XS was written by Marc Lehmann <schmorp[at]schmorp.de>
  1504. The relese of this new version owes to the courtesy of Marc Lehmann.
  1505. =head1 COPYRIGHT AND LICENSE
  1506. Copyright 2005-2011 by Makamaka Hannyaharamitu
  1507. This library is free software; you can redistribute it and/or modify
  1508. it under the same terms as Perl itself.
  1509. =cut